clang  15.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/Lookup.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
41 #include "clang/Sema/Template.h"
42 #include "llvm/ADT/ScopeExit.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include <map>
47 #include <set>
48 
49 using namespace clang;
50 
51 //===----------------------------------------------------------------------===//
52 // CheckDefaultArgumentVisitor
53 //===----------------------------------------------------------------------===//
54 
55 namespace {
56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57 /// the default argument of a parameter to determine whether it
58 /// contains any ill-formed subexpressions. For example, this will
59 /// diagnose the use of local variables or parameters within the
60 /// default argument expression.
61 class CheckDefaultArgumentVisitor
62  : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63  Sema &S;
64  const Expr *DefaultArg;
65 
66 public:
67  CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68  : S(S), DefaultArg(DefaultArg) {}
69 
70  bool VisitExpr(const Expr *Node);
71  bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72  bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73  bool VisitLambdaExpr(const LambdaExpr *Lambda);
74  bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75 };
76 
77 /// VisitExpr - Visit all of the children of this expression.
78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79  bool IsInvalid = false;
80  for (const Stmt *SubStmt : Node->children())
81  IsInvalid |= Visit(SubStmt);
82  return IsInvalid;
83 }
84 
85 /// VisitDeclRefExpr - Visit a reference to a declaration, to
86 /// determine whether this declaration can be used in the default
87 /// argument expression.
88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89  const NamedDecl *Decl = DRE->getDecl();
90  if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91  // C++ [dcl.fct.default]p9:
92  // [...] parameters of a function shall not be used in default
93  // argument expressions, even if they are not evaluated. [...]
94  //
95  // C++17 [dcl.fct.default]p9 (by CWG 2082):
96  // [...] A parameter shall not appear as a potentially-evaluated
97  // expression in a default argument. [...]
98  //
99  if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100  return S.Diag(DRE->getBeginLoc(),
101  diag::err_param_default_argument_references_param)
102  << Param->getDeclName() << DefaultArg->getSourceRange();
103  } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104  // C++ [dcl.fct.default]p7:
105  // Local variables shall not be used in default argument
106  // expressions.
107  //
108  // C++17 [dcl.fct.default]p7 (by CWG 2082):
109  // A local variable shall not appear as a potentially-evaluated
110  // expression in a default argument.
111  //
112  // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113  // Note: A local variable cannot be odr-used (6.3) in a default argument.
114  //
115  if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
116  return S.Diag(DRE->getBeginLoc(),
117  diag::err_param_default_argument_references_local)
118  << VDecl->getDeclName() << DefaultArg->getSourceRange();
119  }
120 
121  return false;
122 }
123 
124 /// VisitCXXThisExpr - Visit a C++ "this" expression.
125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126  // C++ [dcl.fct.default]p8:
127  // The keyword this shall not be used in a default argument of a
128  // member function.
129  return S.Diag(ThisE->getBeginLoc(),
130  diag::err_param_default_argument_references_this)
131  << ThisE->getSourceRange();
132 }
133 
134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135  const PseudoObjectExpr *POE) {
136  bool Invalid = false;
137  for (const Expr *E : POE->semantics()) {
138  // Look through bindings.
139  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140  E = OVE->getSourceExpr();
141  assert(E && "pseudo-object binding without source expression?");
142  }
143 
144  Invalid |= Visit(E);
145  }
146  return Invalid;
147 }
148 
149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150  // C++11 [expr.lambda.prim]p13:
151  // A lambda-expression appearing in a default argument shall not
152  // implicitly or explicitly capture any entity.
153  if (Lambda->capture_begin() == Lambda->capture_end())
154  return false;
155 
156  return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157 }
158 } // namespace
159 
160 void
162  const CXXMethodDecl *Method) {
163  // If we have an MSAny spec already, don't bother.
164  if (!Method || ComputedEST == EST_MSAny)
165  return;
166 
167  const FunctionProtoType *Proto
168  = Method->getType()->getAs<FunctionProtoType>();
169  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170  if (!Proto)
171  return;
172 
174 
175  // If we have a throw-all spec at this point, ignore the function.
176  if (ComputedEST == EST_None)
177  return;
178 
179  if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
180  EST = EST_BasicNoexcept;
181 
182  switch (EST) {
183  case EST_Unparsed:
184  case EST_Uninstantiated:
185  case EST_Unevaluated:
186  llvm_unreachable("should not see unresolved exception specs here");
187 
188  // If this function can throw any exceptions, make a note of that.
189  case EST_MSAny:
190  case EST_None:
191  // FIXME: Whichever we see last of MSAny and None determines our result.
192  // We should make a consistent, order-independent choice here.
193  ClearExceptions();
194  ComputedEST = EST;
195  return;
196  case EST_NoexceptFalse:
197  ClearExceptions();
198  ComputedEST = EST_None;
199  return;
200  // FIXME: If the call to this decl is using any of its default arguments, we
201  // need to search them for potentially-throwing calls.
202  // If this function has a basic noexcept, it doesn't affect the outcome.
203  case EST_BasicNoexcept:
204  case EST_NoexceptTrue:
205  case EST_NoThrow:
206  return;
207  // If we're still at noexcept(true) and there's a throw() callee,
208  // change to that specification.
209  case EST_DynamicNone:
210  if (ComputedEST == EST_BasicNoexcept)
211  ComputedEST = EST_DynamicNone;
212  return;
214  llvm_unreachable(
215  "should not generate implicit declarations for dependent cases");
216  case EST_Dynamic:
217  break;
218  }
219  assert(EST == EST_Dynamic && "EST case not considered earlier.");
220  assert(ComputedEST != EST_None &&
221  "Shouldn't collect exceptions when throw-all is guaranteed.");
222  ComputedEST = EST_Dynamic;
223  // Record the exceptions in this function's exception specification.
224  for (const auto &E : Proto->exceptions())
225  if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226  Exceptions.push_back(E);
227 }
228 
230  if (!S || ComputedEST == EST_MSAny)
231  return;
232 
233  // FIXME:
234  //
235  // C++0x [except.spec]p14:
236  // [An] implicit exception-specification specifies the type-id T if and
237  // only if T is allowed by the exception-specification of a function directly
238  // invoked by f's implicit definition; f shall allow all exceptions if any
239  // function it directly invokes allows all exceptions, and f shall allow no
240  // exceptions if every function it directly invokes allows no exceptions.
241  //
242  // Note in particular that if an implicit exception-specification is generated
243  // for a function containing a throw-expression, that specification can still
244  // be noexcept(true).
245  //
246  // Note also that 'directly invoked' is not defined in the standard, and there
247  // is no indication that we should only consider potentially-evaluated calls.
248  //
249  // Ultimately we should implement the intent of the standard: the exception
250  // specification should be the set of exceptions which can be thrown by the
251  // implicit definition. For now, we assume that any non-nothrow expression can
252  // throw any exception.
253 
254  if (Self->canThrow(S))
255  ComputedEST = EST_None;
256 }
257 
259  SourceLocation EqualLoc) {
260  if (RequireCompleteType(Param->getLocation(), Param->getType(),
261  diag::err_typecheck_decl_incomplete_type))
262  return true;
263 
264  // C++ [dcl.fct.default]p5
265  // A default argument expression is implicitly converted (clause
266  // 4) to the parameter type. The default argument expression has
267  // the same semantic constraints as the initializer expression in
268  // a declaration of a variable of the parameter type, using the
269  // copy-initialization semantics (8.5).
271  Param);
273  EqualLoc);
274  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276  if (Result.isInvalid())
277  return true;
278  Arg = Result.getAs<Expr>();
279 
280  CheckCompletedExpr(Arg, EqualLoc);
281  Arg = MaybeCreateExprWithCleanups(Arg);
282 
283  return Arg;
284 }
285 
287  SourceLocation EqualLoc) {
288  // Add the default argument to the parameter
289  Param->setDefaultArg(Arg);
290 
291  // We have already instantiated this parameter; provide each of the
292  // instantiations with the uninstantiated default argument.
293  UnparsedDefaultArgInstantiationsMap::iterator InstPos
294  = UnparsedDefaultArgInstantiations.find(Param);
295  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296  for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297  InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298 
299  // We're done tracking this parameter's instantiations.
300  UnparsedDefaultArgInstantiations.erase(InstPos);
301  }
302 }
303 
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
307 void
309  Expr *DefaultArg) {
310  if (!param || !DefaultArg)
311  return;
312 
313  ParmVarDecl *Param = cast<ParmVarDecl>(param);
314  UnparsedDefaultArgLocs.erase(Param);
315 
316  auto Fail = [&] {
317  Param->setInvalidDecl();
319  EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320  };
321 
322  // Default arguments are only permitted in C++
323  if (!getLangOpts().CPlusPlus) {
324  Diag(EqualLoc, diag::err_param_default_argument)
325  << DefaultArg->getSourceRange();
326  return Fail();
327  }
328 
329  // Check for unexpanded parameter packs.
331  return Fail();
332  }
333 
334  // C++11 [dcl.fct.default]p3
335  // A default argument expression [...] shall not be specified for a
336  // parameter pack.
337  if (Param->isParameterPack()) {
338  Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339  << DefaultArg->getSourceRange();
340  // Recover by discarding the default argument.
341  Param->setDefaultArg(nullptr);
342  return;
343  }
344 
345  ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346  if (Result.isInvalid())
347  return Fail();
348 
349  DefaultArg = Result.getAs<Expr>();
350 
351  // Check that the default argument is well-formed
352  CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353  if (DefaultArgChecker.Visit(DefaultArg))
354  return Fail();
355 
356  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357 }
358 
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
364  SourceLocation EqualLoc,
365  SourceLocation ArgLoc) {
366  if (!param)
367  return;
368 
369  ParmVarDecl *Param = cast<ParmVarDecl>(param);
370  Param->setUnparsedDefaultArg();
371  UnparsedDefaultArgLocs[Param] = ArgLoc;
372 }
373 
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
377  SourceLocation EqualLoc) {
378  if (!param)
379  return;
380 
381  ParmVarDecl *Param = cast<ParmVarDecl>(param);
382  Param->setInvalidDecl();
383  UnparsedDefaultArgLocs.erase(Param);
385  EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386 }
387 
388 /// CheckExtraCXXDefaultArguments - Check for any extra default
389 /// arguments in the declarator, which is not a function declaration
390 /// or definition and therefore is not permitted to have default
391 /// arguments. This routine should be invoked for every declarator
392 /// that is not a function declaration or definition.
394  // C++ [dcl.fct.default]p3
395  // A default argument expression shall be specified only in the
396  // parameter-declaration-clause of a function declaration or in a
397  // template-parameter (14.1). It shall not be specified for a
398  // parameter pack. If it is specified in a
399  // parameter-declaration-clause, it shall not occur within a
400  // declarator or abstract-declarator of a parameter-declaration.
401  bool MightBeFunction = D.isFunctionDeclarationContext();
402  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
403  DeclaratorChunk &chunk = D.getTypeObject(i);
404  if (chunk.Kind == DeclaratorChunk::Function) {
405  if (MightBeFunction) {
406  // This is a function declaration. It can have default arguments, but
407  // keep looking in case its return type is a function type with default
408  // arguments.
409  MightBeFunction = false;
410  continue;
411  }
412  for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
413  ++argIdx) {
414  ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415  if (Param->hasUnparsedDefaultArg()) {
416  std::unique_ptr<CachedTokens> Toks =
417  std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418  SourceRange SR;
419  if (Toks->size() > 1)
420  SR = SourceRange((*Toks)[1].getLocation(),
421  Toks->back().getLocation());
422  else
423  SR = UnparsedDefaultArgLocs[Param];
424  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425  << SR;
426  } else if (Param->getDefaultArg()) {
427  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428  << Param->getDefaultArg()->getSourceRange();
429  Param->setDefaultArg(nullptr);
430  }
431  }
432  } else if (chunk.Kind != DeclaratorChunk::Paren) {
433  MightBeFunction = false;
434  }
435  }
436 }
437 
439  return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440  return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
441  });
442 }
443 
444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
445 /// function, once we already know that they have the same
446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447 /// error, false otherwise.
449  Scope *S) {
450  bool Invalid = false;
451 
452  // The declaration context corresponding to the scope is the semantic
453  // parent, unless this is a local function declaration, in which case
454  // it is that surrounding function.
455  DeclContext *ScopeDC = New->isLocalExternDecl()
456  ? New->getLexicalDeclContext()
457  : New->getDeclContext();
458 
459  // Find the previous declaration for the purpose of default arguments.
460  FunctionDecl *PrevForDefaultArgs = Old;
461  for (/**/; PrevForDefaultArgs;
462  // Don't bother looking back past the latest decl if this is a local
463  // extern declaration; nothing else could work.
464  PrevForDefaultArgs = New->isLocalExternDecl()
465  ? nullptr
466  : PrevForDefaultArgs->getPreviousDecl()) {
467  // Ignore hidden declarations.
468  if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469  continue;
470 
471  if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
472  !New->isCXXClassMember()) {
473  // Ignore default arguments of old decl if they are not in
474  // the same scope and this is not an out-of-line definition of
475  // a member function.
476  continue;
477  }
478 
479  if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480  // If only one of these is a local function declaration, then they are
481  // declared in different scopes, even though isDeclInScope may think
482  // they're in the same scope. (If both are local, the scope check is
483  // sufficient, and if neither is local, then they are in the same scope.)
484  continue;
485  }
486 
487  // We found the right previous declaration.
488  break;
489  }
490 
491  // C++ [dcl.fct.default]p4:
492  // For non-template functions, default arguments can be added in
493  // later declarations of a function in the same
494  // scope. Declarations in different scopes have completely
495  // distinct sets of default arguments. That is, declarations in
496  // inner scopes do not acquire default arguments from
497  // declarations in outer scopes, and vice versa. In a given
498  // function declaration, all parameters subsequent to a
499  // parameter with a default argument shall have default
500  // arguments supplied in this or previous declarations. A
501  // default argument shall not be redefined by a later
502  // declaration (not even to the same value).
503  //
504  // C++ [dcl.fct.default]p6:
505  // Except for member functions of class templates, the default arguments
506  // in a member function definition that appears outside of the class
507  // definition are added to the set of default arguments provided by the
508  // member function declaration in the class definition.
509  for (unsigned p = 0, NumParams = PrevForDefaultArgs
510  ? PrevForDefaultArgs->getNumParams()
511  : 0;
512  p < NumParams; ++p) {
513  ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
514  ParmVarDecl *NewParam = New->getParamDecl(p);
515 
516  bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
517  bool NewParamHasDfl = NewParam->hasDefaultArg();
518 
519  if (OldParamHasDfl && NewParamHasDfl) {
520  unsigned DiagDefaultParamID =
521  diag::err_param_default_argument_redefinition;
522 
523  // MSVC accepts that default parameters be redefined for member functions
524  // of template class. The new default parameter's value is ignored.
525  Invalid = true;
526  if (getLangOpts().MicrosoftExt) {
527  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
528  if (MD && MD->getParent()->getDescribedClassTemplate()) {
529  // Merge the old default argument into the new parameter.
530  NewParam->setHasInheritedDefaultArg();
531  if (OldParam->hasUninstantiatedDefaultArg())
532  NewParam->setUninstantiatedDefaultArg(
533  OldParam->getUninstantiatedDefaultArg());
534  else
535  NewParam->setDefaultArg(OldParam->getInit());
536  DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
537  Invalid = false;
538  }
539  }
540 
541  // FIXME: If we knew where the '=' was, we could easily provide a fix-it
542  // hint here. Alternatively, we could walk the type-source information
543  // for NewParam to find the last source location in the type... but it
544  // isn't worth the effort right now. This is the kind of test case that
545  // is hard to get right:
546  // int f(int);
547  // void g(int (*fp)(int) = f);
548  // void g(int (*fp)(int) = &f);
549  Diag(NewParam->getLocation(), DiagDefaultParamID)
550  << NewParam->getDefaultArgRange();
551 
552  // Look for the function declaration where the default argument was
553  // actually written, which may be a declaration prior to Old.
554  for (auto Older = PrevForDefaultArgs;
555  OldParam->hasInheritedDefaultArg(); /**/) {
556  Older = Older->getPreviousDecl();
557  OldParam = Older->getParamDecl(p);
558  }
559 
560  Diag(OldParam->getLocation(), diag::note_previous_definition)
561  << OldParam->getDefaultArgRange();
562  } else if (OldParamHasDfl) {
563  // Merge the old default argument into the new parameter unless the new
564  // function is a friend declaration in a template class. In the latter
565  // case the default arguments will be inherited when the friend
566  // declaration will be instantiated.
567  if (New->getFriendObjectKind() == Decl::FOK_None ||
569  // It's important to use getInit() here; getDefaultArg()
570  // strips off any top-level ExprWithCleanups.
571  NewParam->setHasInheritedDefaultArg();
572  if (OldParam->hasUnparsedDefaultArg())
573  NewParam->setUnparsedDefaultArg();
574  else if (OldParam->hasUninstantiatedDefaultArg())
575  NewParam->setUninstantiatedDefaultArg(
576  OldParam->getUninstantiatedDefaultArg());
577  else
578  NewParam->setDefaultArg(OldParam->getInit());
579  }
580  } else if (NewParamHasDfl) {
581  if (New->getDescribedFunctionTemplate()) {
582  // Paragraph 4, quoted above, only applies to non-template functions.
583  Diag(NewParam->getLocation(),
584  diag::err_param_default_argument_template_redecl)
585  << NewParam->getDefaultArgRange();
586  Diag(PrevForDefaultArgs->getLocation(),
587  diag::note_template_prev_declaration)
588  << false;
589  } else if (New->getTemplateSpecializationKind()
592  // C++ [temp.expr.spec]p21:
593  // Default function arguments shall not be specified in a declaration
594  // or a definition for one of the following explicit specializations:
595  // - the explicit specialization of a function template;
596  // - the explicit specialization of a member function template;
597  // - the explicit specialization of a member function of a class
598  // template where the class template specialization to which the
599  // member function specialization belongs is implicitly
600  // instantiated.
601  Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
603  << New->getDeclName()
604  << NewParam->getDefaultArgRange();
605  } else if (New->getDeclContext()->isDependentContext()) {
606  // C++ [dcl.fct.default]p6 (DR217):
607  // Default arguments for a member function of a class template shall
608  // be specified on the initial declaration of the member function
609  // within the class template.
610  //
611  // Reading the tea leaves a bit in DR217 and its reference to DR205
612  // leads me to the conclusion that one cannot add default function
613  // arguments for an out-of-line definition of a member function of a
614  // dependent type.
615  int WhichKind = 2;
616  if (CXXRecordDecl *Record
617  = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
618  if (Record->getDescribedClassTemplate())
619  WhichKind = 0;
620  else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
621  WhichKind = 1;
622  else
623  WhichKind = 2;
624  }
625 
626  Diag(NewParam->getLocation(),
627  diag::err_param_default_argument_member_template_redecl)
628  << WhichKind
629  << NewParam->getDefaultArgRange();
630  }
631  }
632  }
633 
634  // DR1344: If a default argument is added outside a class definition and that
635  // default argument makes the function a special member function, the program
636  // is ill-formed. This can only happen for constructors.
637  if (isa<CXXConstructorDecl>(New) &&
639  CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
640  OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
641  if (NewSM != OldSM) {
642  ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
643  assert(NewParam->hasDefaultArg());
644  Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
645  << NewParam->getDefaultArgRange() << NewSM;
646  Diag(Old->getLocation(), diag::note_previous_declaration);
647  }
648  }
649 
650  const FunctionDecl *Def;
651  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
652  // template has a constexpr specifier then all its declarations shall
653  // contain the constexpr specifier.
654  if (New->getConstexprKind() != Old->getConstexprKind()) {
655  Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
656  << New << static_cast<int>(New->getConstexprKind())
657  << static_cast<int>(Old->getConstexprKind());
658  Diag(Old->getLocation(), diag::note_previous_declaration);
659  Invalid = true;
660  } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
661  Old->isDefined(Def) &&
662  // If a friend function is inlined but does not have 'inline'
663  // specifier, it is a definition. Do not report attribute conflict
664  // in this case, redefinition will be diagnosed later.
665  (New->isInlineSpecified() ||
666  New->getFriendObjectKind() == Decl::FOK_None)) {
667  // C++11 [dcl.fcn.spec]p4:
668  // If the definition of a function appears in a translation unit before its
669  // first declaration as inline, the program is ill-formed.
670  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
671  Diag(Def->getLocation(), diag::note_previous_definition);
672  Invalid = true;
673  }
674 
675  // C++17 [temp.deduct.guide]p3:
676  // Two deduction guide declarations in the same translation unit
677  // for the same class template shall not have equivalent
678  // parameter-declaration-clauses.
679  if (isa<CXXDeductionGuideDecl>(New) &&
681  Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
682  Diag(Old->getLocation(), diag::note_previous_declaration);
683  }
684 
685  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
686  // argument expression, that declaration shall be a definition and shall be
687  // the only declaration of the function or function template in the
688  // translation unit.
691  Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
692  Diag(Old->getLocation(), diag::note_previous_declaration);
693  Invalid = true;
694  }
695 
696  // C++11 [temp.friend]p4 (DR329):
697  // When a function is defined in a friend function declaration in a class
698  // template, the function is instantiated when the function is odr-used.
699  // The same restrictions on multiple declarations and definitions that
700  // apply to non-template function declarations and definitions also apply
701  // to these implicit definitions.
702  const FunctionDecl *OldDefinition = nullptr;
704  Old->isDefined(OldDefinition, true))
705  CheckForFunctionRedefinition(New, OldDefinition);
706 
707  return Invalid;
708 }
709 
710 NamedDecl *
712  MultiTemplateParamsArg TemplateParamLists) {
713  assert(D.isDecompositionDeclarator());
715 
716  // The syntax only allows a decomposition declarator as a simple-declaration,
717  // a for-range-declaration, or a condition in Clang, but we parse it in more
718  // cases than that.
720  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
721  << Decomp.getSourceRange();
722  return nullptr;
723  }
724 
725  if (!TemplateParamLists.empty()) {
726  // FIXME: There's no rule against this, but there are also no rules that
727  // would actually make it usable, so we reject it for now.
728  Diag(TemplateParamLists.front()->getTemplateLoc(),
729  diag::err_decomp_decl_template);
730  return nullptr;
731  }
732 
733  Diag(Decomp.getLSquareLoc(),
735  ? diag::ext_decomp_decl
737  ? diag::ext_decomp_decl_cond
738  : diag::warn_cxx14_compat_decomp_decl)
739  << Decomp.getSourceRange();
740 
741  // The semantic context is always just the current context.
742  DeclContext *const DC = CurContext;
743 
744  // C++17 [dcl.dcl]/8:
745  // The decl-specifier-seq shall contain only the type-specifier auto
746  // and cv-qualifiers.
747  // C++2a [dcl.dcl]/8:
748  // If decl-specifier-seq contains any decl-specifier other than static,
749  // thread_local, auto, or cv-qualifiers, the program is ill-formed.
750  auto &DS = D.getDeclSpec();
751  {
752  SmallVector<StringRef, 8> BadSpecifiers;
753  SmallVector<SourceLocation, 8> BadSpecifierLocs;
754  SmallVector<StringRef, 8> CPlusPlus20Specifiers;
755  SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
756  if (auto SCS = DS.getStorageClassSpec()) {
757  if (SCS == DeclSpec::SCS_static) {
758  CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
759  CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
760  } else {
761  BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
762  BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
763  }
764  }
765  if (auto TSCS = DS.getThreadStorageClassSpec()) {
766  CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
767  CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
768  }
769  if (DS.hasConstexprSpecifier()) {
770  BadSpecifiers.push_back(
771  DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
772  BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
773  }
774  if (DS.isInlineSpecified()) {
775  BadSpecifiers.push_back("inline");
776  BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
777  }
778  if (!BadSpecifiers.empty()) {
779  auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
780  Err << (int)BadSpecifiers.size()
781  << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
782  // Don't add FixItHints to remove the specifiers; we do still respect
783  // them when building the underlying variable.
784  for (auto Loc : BadSpecifierLocs)
785  Err << SourceRange(Loc, Loc);
786  } else if (!CPlusPlus20Specifiers.empty()) {
787  auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
789  ? diag::warn_cxx17_compat_decomp_decl_spec
790  : diag::ext_decomp_decl_spec);
791  Warn << (int)CPlusPlus20Specifiers.size()
792  << llvm::join(CPlusPlus20Specifiers.begin(),
793  CPlusPlus20Specifiers.end(), " ");
794  for (auto Loc : CPlusPlus20SpecifierLocs)
795  Warn << SourceRange(Loc, Loc);
796  }
797  // We can't recover from it being declared as a typedef.
798  if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
799  return nullptr;
800  }
801 
802  // C++2a [dcl.struct.bind]p1:
803  // A cv that includes volatile is deprecated
804  if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
806  Diag(DS.getVolatileSpecLoc(),
807  diag::warn_deprecated_volatile_structured_binding);
808 
809  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
810  QualType R = TInfo->getType();
811 
814  D.setInvalidType();
815 
816  // The syntax only allows a single ref-qualifier prior to the decomposition
817  // declarator. No other declarator chunks are permitted. Also check the type
818  // specifier here.
819  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
820  D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
821  (D.getNumTypeObjects() == 1 &&
823  Diag(Decomp.getLSquareLoc(),
824  (D.hasGroupingParens() ||
825  (D.getNumTypeObjects() &&
827  ? diag::err_decomp_decl_parens
828  : diag::err_decomp_decl_type)
829  << R;
830 
831  // In most cases, there's no actual problem with an explicitly-specified
832  // type, but a function type won't work here, and ActOnVariableDeclarator
833  // shouldn't be called for such a type.
834  if (R->isFunctionType())
835  D.setInvalidType();
836  }
837 
838  // Build the BindingDecls.
840 
841  // Build the BindingDecls.
842  for (auto &B : D.getDecompositionDeclarator().bindings()) {
843  // Check for name conflicts.
844  DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
845  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847  LookupName(Previous, S,
848  /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
849 
850  // It's not permitted to shadow a template parameter name.
851  if (Previous.isSingleResult() &&
852  Previous.getFoundDecl()->isTemplateParameter()) {
854  Previous.getFoundDecl());
855  Previous.clear();
856  }
857 
858  auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859 
860  // Find the shadowed declaration before filtering for scope.
861  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
863  : nullptr;
864 
865  bool ConsiderLinkage = DC->isFunctionOrMethod() &&
866  DS.getStorageClassSpec() == DeclSpec::SCS_extern;
867  FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
868  /*AllowInlineNamespace*/false);
869 
870  if (!Previous.empty()) {
871  auto *Old = Previous.getRepresentativeDecl();
872  Diag(B.NameLoc, diag::err_redefinition) << B.Name;
873  Diag(Old->getLocation(), diag::note_previous_definition);
874  } else if (ShadowedDecl && !D.isRedeclaration()) {
875  CheckShadow(BD, ShadowedDecl, Previous);
876  }
877  PushOnScopeChains(BD, S, true);
878  Bindings.push_back(BD);
879  ParsingInitForAutoVars.insert(BD);
880  }
881 
882  // There are no prior lookup results for the variable itself, because it
883  // is unnamed.
884  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
885  Decomp.getLSquareLoc());
886  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
888 
889  // Build the variable that holds the non-decomposed object.
890  bool AddToScope = true;
891  NamedDecl *New =
892  ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
893  MultiTemplateParamsArg(), AddToScope, Bindings);
894  if (AddToScope) {
895  S->AddDecl(New);
897  }
898 
900  checkDeclIsAllowedInOpenMPTarget(nullptr, New);
901 
902  return New;
903 }
904 
907  QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
908  llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
909  if ((int64_t)Bindings.size() != NumElems) {
910  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
911  << DecompType << (unsigned)Bindings.size()
912  << (unsigned)NumElems.getLimitedValue(UINT_MAX)
913  << toString(NumElems, 10) << (NumElems < Bindings.size());
914  return true;
915  }
916 
917  unsigned I = 0;
918  for (auto *B : Bindings) {
919  SourceLocation Loc = B->getLocation();
920  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
921  if (E.isInvalid())
922  return true;
923  E = GetInit(Loc, E.get(), I++);
924  if (E.isInvalid())
925  return true;
926  B->setBinding(ElemType, E.get());
927  }
928 
929  return false;
930 }
931 
934  ValueDecl *Src, QualType DecompType,
935  const llvm::APSInt &NumElems,
936  QualType ElemType) {
938  S, Bindings, Src, DecompType, NumElems, ElemType,
939  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940  ExprResult E = S.ActOnIntegerConstant(Loc, I);
941  if (E.isInvalid())
942  return ExprError();
943  return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
944  });
945 }
946 
948  ValueDecl *Src, QualType DecompType,
949  const ConstantArrayType *CAT) {
950  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
951  llvm::APSInt(CAT->getSize()),
952  CAT->getElementType());
953 }
954 
956  ValueDecl *Src, QualType DecompType,
957  const VectorType *VT) {
959  S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
961  DecompType.getQualifiers()));
962 }
963 
966  ValueDecl *Src, QualType DecompType,
967  const ComplexType *CT) {
969  S, Bindings, Src, DecompType, llvm::APSInt::get(2),
971  DecompType.getQualifiers()),
972  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973  return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
974  });
975 }
976 
979  const TemplateParameterList *Params) {
980  SmallString<128> SS;
981  llvm::raw_svector_ostream OS(SS);
982  bool First = true;
983  unsigned I = 0;
984  for (auto &Arg : Args.arguments()) {
985  if (!First)
986  OS << ", ";
987  Arg.getArgument().print(PrintingPolicy, OS,
989  PrintingPolicy, Params, I));
990  First = false;
991  I++;
992  }
993  return std::string(OS.str());
994 }
995 
996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
997  SourceLocation Loc, StringRef Trait,
999  unsigned DiagID) {
1000  auto DiagnoseMissing = [&] {
1001  if (DiagID)
1002  S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1003  Args, /*Params*/ nullptr);
1004  return true;
1005  };
1006 
1007  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1009  if (!Std)
1010  return DiagnoseMissing();
1011 
1012  // Look up the trait itself, within namespace std. We can diagnose various
1013  // problems with this lookup even if we've been asked to not diagnose a
1014  // missing specialization, because this can only fail if the user has been
1015  // declaring their own names in namespace std or we don't support the
1016  // standard library implementation in use.
1017  LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1019  if (!S.LookupQualifiedName(Result, Std))
1020  return DiagnoseMissing();
1021  if (Result.isAmbiguous())
1022  return true;
1023 
1024  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1025  if (!TraitTD) {
1026  Result.suppressDiagnostics();
1027  NamedDecl *Found = *Result.begin();
1028  S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1029  S.Diag(Found->getLocation(), diag::note_declared_at);
1030  return true;
1031  }
1032 
1033  // Build the template-id.
1034  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1035  if (TraitTy.isNull())
1036  return true;
1037  if (!S.isCompleteType(Loc, TraitTy)) {
1038  if (DiagID)
1040  Loc, TraitTy, DiagID,
1042  TraitTD->getTemplateParameters()));
1043  return true;
1044  }
1045 
1046  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1047  assert(RD && "specialization of class template is not a class?");
1048 
1049  // Look up the member of the trait type.
1050  S.LookupQualifiedName(TraitMemberLookup, RD);
1051  return TraitMemberLookup.isAmbiguous();
1052 }
1053 
1054 static TemplateArgumentLoc
1056  uint64_t I) {
1057  TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1058  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1059 }
1060 
1061 static TemplateArgumentLoc
1064 }
1065 
1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1067 
1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1069  llvm::APSInt &Size) {
1072 
1075 
1076  // Form template argument list for tuple_size<T>.
1077  TemplateArgumentListInfo Args(Loc, Loc);
1079 
1080  // If there's no tuple_size specialization or the lookup of 'value' is empty,
1081  // it's not tuple-like.
1082  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1083  R.empty())
1084  return IsTupleLike::NotTupleLike;
1085 
1086  // If we get this far, we've committed to the tuple interpretation, but
1087  // we can still fail if there actually isn't a usable ::value.
1088 
1089  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1090  LookupResult &R;
1092  ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1093  : R(R), Args(Args) {}
1094  Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1095  SourceLocation Loc) override {
1096  return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1098  /*Params*/ nullptr);
1099  }
1100  } Diagnoser(R, Args);
1101 
1102  ExprResult E =
1103  S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1104  if (E.isInvalid())
1105  return IsTupleLike::Error;
1106 
1107  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1108  if (E.isInvalid())
1109  return IsTupleLike::Error;
1110 
1111  return IsTupleLike::TupleLike;
1112 }
1113 
1114 /// \return std::tuple_element<I, T>::type.
1116  unsigned I, QualType T) {
1117  // Form template argument list for tuple_element<I, T>.
1118  TemplateArgumentListInfo Args(Loc, Loc);
1119  Args.addArgument(
1122 
1123  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1124  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1126  S, R, Loc, "tuple_element", Args,
1127  diag::err_decomp_decl_std_tuple_element_not_specialized))
1128  return QualType();
1129 
1130  auto *TD = R.getAsSingle<TypeDecl>();
1131  if (!TD) {
1132  R.suppressDiagnostics();
1133  S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1135  /*Params*/ nullptr);
1136  if (!R.empty())
1137  S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1138  return QualType();
1139  }
1140 
1141  return S.Context.getTypeDeclType(TD);
1142 }
1143 
1144 namespace {
1145 struct InitializingBinding {
1146  Sema &S;
1147  InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1150  Ctx.PointOfInstantiation = BD->getLocation();
1151  Ctx.Entity = BD;
1152  S.pushCodeSynthesisContext(Ctx);
1153  }
1154  ~InitializingBinding() {
1156  }
1157 };
1158 }
1159 
1162  VarDecl *Src, QualType DecompType,
1163  const llvm::APSInt &TupleSize) {
1164  if ((int64_t)Bindings.size() != TupleSize) {
1165  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1166  << DecompType << (unsigned)Bindings.size()
1167  << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1168  << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1169  return true;
1170  }
1171 
1172  if (Bindings.empty())
1173  return false;
1174 
1175  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1176 
1177  // [dcl.decomp]p3:
1178  // The unqualified-id get is looked up in the scope of E by class member
1179  // access lookup ...
1180  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1181  bool UseMemberGet = false;
1182  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1183  if (auto *RD = DecompType->getAsCXXRecordDecl())
1184  S.LookupQualifiedName(MemberGet, RD);
1185  if (MemberGet.isAmbiguous())
1186  return true;
1187  // ... and if that finds at least one declaration that is a function
1188  // template whose first template parameter is a non-type parameter ...
1189  for (NamedDecl *D : MemberGet) {
1190  if (FunctionTemplateDecl *FTD =
1191  dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1192  TemplateParameterList *TPL = FTD->getTemplateParameters();
1193  if (TPL->size() != 0 &&
1194  isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1195  // ... the initializer is e.get<i>().
1196  UseMemberGet = true;
1197  break;
1198  }
1199  }
1200  }
1201  }
1202 
1203  unsigned I = 0;
1204  for (auto *B : Bindings) {
1205  InitializingBinding InitContext(S, B);
1206  SourceLocation Loc = B->getLocation();
1207 
1208  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1209  if (E.isInvalid())
1210  return true;
1211 
1212  // e is an lvalue if the type of the entity is an lvalue reference and
1213  // an xvalue otherwise
1214  if (!Src->getType()->isLValueReferenceType())
1215  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1216  E.get(), nullptr, VK_XValue,
1217  FPOptionsOverride());
1218 
1219  TemplateArgumentListInfo Args(Loc, Loc);
1220  Args.addArgument(
1222 
1223  if (UseMemberGet) {
1224  // if [lookup of member get] finds at least one declaration, the
1225  // initializer is e.get<i-1>().
1226  E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1227  CXXScopeSpec(), SourceLocation(), nullptr,
1228  MemberGet, &Args, nullptr);
1229  if (E.isInvalid())
1230  return true;
1231 
1232  E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1233  } else {
1234  // Otherwise, the initializer is get<i-1>(e), where get is looked up
1235  // in the associated namespaces.
1238  DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1240 
1241  Expr *Arg = E.get();
1242  E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1243  }
1244  if (E.isInvalid())
1245  return true;
1246  Expr *Init = E.get();
1247 
1248  // Given the type T designated by std::tuple_element<i - 1, E>::type,
1249  QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1250  if (T.isNull())
1251  return true;
1252 
1253  // each vi is a variable of type "reference to T" initialized with the
1254  // initializer, where the reference is an lvalue reference if the
1255  // initializer is an lvalue and an rvalue reference otherwise
1256  QualType RefType =
1257  S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1258  if (RefType.isNull())
1259  return true;
1260  auto *RefVD = VarDecl::Create(
1261  S.Context, Src->getDeclContext(), Loc, Loc,
1262  B->getDeclName().getAsIdentifierInfo(), RefType,
1264  RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1265  RefVD->setTSCSpec(Src->getTSCSpec());
1266  RefVD->setImplicit();
1267  if (Src->isInlineSpecified())
1268  RefVD->setInlineSpecified();
1269  RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1270 
1273  InitializationSequence Seq(S, Entity, Kind, Init);
1274  E = Seq.Perform(S, Entity, Kind, Init);
1275  if (E.isInvalid())
1276  return true;
1277  E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1278  if (E.isInvalid())
1279  return true;
1280  RefVD->setInit(E.get());
1282 
1284  DeclarationNameInfo(B->getDeclName(), Loc),
1285  RefVD);
1286  if (E.isInvalid())
1287  return true;
1288 
1289  B->setBinding(T, E.get());
1290  I++;
1291  }
1292 
1293  return false;
1294 }
1295 
1296 /// Find the base class to decompose in a built-in decomposition of a class type.
1297 /// This base class search is, unfortunately, not quite like any other that we
1298 /// perform anywhere else in C++.
1300  const CXXRecordDecl *RD,
1301  CXXCastPath &BasePath) {
1302  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1303  CXXBasePath &Path) {
1304  return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1305  };
1306 
1307  const CXXRecordDecl *ClassWithFields = nullptr;
1309  if (RD->hasDirectFields())
1310  // [dcl.decomp]p4:
1311  // Otherwise, all of E's non-static data members shall be public direct
1312  // members of E ...
1313  ClassWithFields = RD;
1314  else {
1315  // ... or of ...
1316  CXXBasePaths Paths;
1317  Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1318  if (!RD->lookupInBases(BaseHasFields, Paths)) {
1319  // If no classes have fields, just decompose RD itself. (This will work
1320  // if and only if zero bindings were provided.)
1321  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1322  }
1323 
1324  CXXBasePath *BestPath = nullptr;
1325  for (auto &P : Paths) {
1326  if (!BestPath)
1327  BestPath = &P;
1328  else if (!S.Context.hasSameType(P.back().Base->getType(),
1329  BestPath->back().Base->getType())) {
1330  // ... the same ...
1331  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1332  << false << RD << BestPath->back().Base->getType()
1333  << P.back().Base->getType();
1334  return DeclAccessPair();
1335  } else if (P.Access < BestPath->Access) {
1336  BestPath = &P;
1337  }
1338  }
1339 
1340  // ... unambiguous ...
1341  QualType BaseType = BestPath->back().Base->getType();
1342  if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1343  S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1344  << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1345  return DeclAccessPair();
1346  }
1347 
1348  // ... [accessible, implied by other rules] base class of E.
1349  S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1350  *BestPath, diag::err_decomp_decl_inaccessible_base);
1351  AS = BestPath->Access;
1352 
1353  ClassWithFields = BaseType->getAsCXXRecordDecl();
1354  S.BuildBasePathArray(Paths, BasePath);
1355  }
1356 
1357  // The above search did not check whether the selected class itself has base
1358  // classes with fields, so check that now.
1359  CXXBasePaths Paths;
1360  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1361  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1362  << (ClassWithFields == RD) << RD << ClassWithFields
1363  << Paths.front().back().Base->getType();
1364  return DeclAccessPair();
1365  }
1366 
1367  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1368 }
1369 
1371  ValueDecl *Src, QualType DecompType,
1372  const CXXRecordDecl *OrigRD) {
1373  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1374  diag::err_incomplete_type))
1375  return true;
1376 
1377  CXXCastPath BasePath;
1378  DeclAccessPair BasePair =
1379  findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1380  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1381  if (!RD)
1382  return true;
1384  DecompType.getQualifiers());
1385 
1386  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1387  unsigned NumFields = llvm::count_if(
1388  RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389  assert(Bindings.size() != NumFields);
1390  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391  << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392  << (NumFields < Bindings.size());
1393  return true;
1394  };
1395 
1396  // all of E's non-static data members shall be [...] well-formed
1397  // when named as e.name in the context of the structured binding,
1398  // E shall not have an anonymous union member, ...
1399  unsigned I = 0;
1400  for (auto *FD : RD->fields()) {
1401  if (FD->isUnnamedBitfield())
1402  continue;
1403 
1404  // All the non-static data members are required to be nameable, so they
1405  // must all have names.
1406  if (!FD->getDeclName()) {
1407  if (RD->isLambda()) {
1408  S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409  S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410  return true;
1411  }
1412 
1413  if (FD->isAnonymousStructOrUnion()) {
1414  S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415  << DecompType << FD->getType()->isUnionType();
1416  S.Diag(FD->getLocation(), diag::note_declared_at);
1417  return true;
1418  }
1419 
1420  // FIXME: Are there any other ways we could have an anonymous member?
1421  }
1422 
1423  // We have a real field to bind.
1424  if (I >= Bindings.size())
1425  return DiagnoseBadNumberOfBindings();
1426  auto *B = Bindings[I++];
1427  SourceLocation Loc = B->getLocation();
1428 
1429  // The field must be accessible in the context of the structured binding.
1430  // We already checked that the base class is accessible.
1431  // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432  // const_cast here.
1434  Loc, const_cast<CXXRecordDecl *>(OrigRD),
1436  BasePair.getAccess(), FD->getAccess())));
1437 
1438  // Initialize the binding to Src.FD.
1439  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440  if (E.isInvalid())
1441  return true;
1442  E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443  VK_LValue, &BasePath);
1444  if (E.isInvalid())
1445  return true;
1446  E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447  CXXScopeSpec(), FD,
1448  DeclAccessPair::make(FD, FD->getAccess()),
1449  DeclarationNameInfo(FD->getDeclName(), Loc));
1450  if (E.isInvalid())
1451  return true;
1452 
1453  // If the type of the member is T, the referenced type is cv T, where cv is
1454  // the cv-qualification of the decomposition expression.
1455  //
1456  // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457  // 'const' to the type of the field.
1458  Qualifiers Q = DecompType.getQualifiers();
1459  if (FD->isMutable())
1460  Q.removeConst();
1461  B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462  }
1463 
1464  if (I != Bindings.size())
1465  return DiagnoseBadNumberOfBindings();
1466 
1467  return false;
1468 }
1469 
1471  QualType DecompType = DD->getType();
1472 
1473  // If the type of the decomposition is dependent, then so is the type of
1474  // each binding.
1475  if (DecompType->isDependentType()) {
1476  for (auto *B : DD->bindings())
1477  B->setType(Context.DependentTy);
1478  return;
1479  }
1480 
1481  DecompType = DecompType.getNonReferenceType();
1483 
1484  // C++1z [dcl.decomp]/2:
1485  // If E is an array type [...]
1486  // As an extension, we also support decomposition of built-in complex and
1487  // vector types.
1488  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489  if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490  DD->setInvalidDecl();
1491  return;
1492  }
1493  if (auto *VT = DecompType->getAs<VectorType>()) {
1494  if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495  DD->setInvalidDecl();
1496  return;
1497  }
1498  if (auto *CT = DecompType->getAs<ComplexType>()) {
1499  if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500  DD->setInvalidDecl();
1501  return;
1502  }
1503 
1504  // C++1z [dcl.decomp]/3:
1505  // if the expression std::tuple_size<E>::value is a well-formed integral
1506  // constant expression, [...]
1507  llvm::APSInt TupleSize(32);
1508  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509  case IsTupleLike::Error:
1510  DD->setInvalidDecl();
1511  return;
1512 
1513  case IsTupleLike::TupleLike:
1514  if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515  DD->setInvalidDecl();
1516  return;
1517 
1518  case IsTupleLike::NotTupleLike:
1519  break;
1520  }
1521 
1522  // C++1z [dcl.dcl]/8:
1523  // [E shall be of array or non-union class type]
1524  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525  if (!RD || RD->isUnion()) {
1526  Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527  << DD << !RD << DecompType;
1528  DD->setInvalidDecl();
1529  return;
1530  }
1531 
1532  // C++1z [dcl.decomp]/4:
1533  // all of E's non-static data members shall be [...] direct members of
1534  // E or of the same unambiguous public base class of E, ...
1535  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536  DD->setInvalidDecl();
1537 }
1538 
1539 /// Merge the exception specifications of two variable declarations.
1540 ///
1541 /// This is called when there's a redeclaration of a VarDecl. The function
1542 /// checks if the redeclaration might have an exception specification and
1543 /// validates compatibility and merges the specs if necessary.
1545  // Shortcut if exceptions are disabled.
1546  if (!getLangOpts().CXXExceptions)
1547  return;
1548 
1549  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1550  "Should only be called if types are otherwise the same.");
1551 
1552  QualType NewType = New->getType();
1553  QualType OldType = Old->getType();
1554 
1555  // We're only interested in pointers and references to functions, as well
1556  // as pointers to member functions.
1557  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558  NewType = R->getPointeeType();
1559  OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561  NewType = P->getPointeeType();
1562  OldType = OldType->castAs<PointerType>()->getPointeeType();
1563  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564  NewType = M->getPointeeType();
1565  OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566  }
1567 
1568  if (!NewType->isFunctionProtoType())
1569  return;
1570 
1571  // There's lots of special cases for functions. For function pointers, system
1572  // libraries are hopefully not as broken so that we don't need these
1573  // workarounds.
1575  OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576  NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577  New->setInvalidDecl();
1578  }
1579 }
1580 
1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1582 /// function declaration are well-formed according to C++
1583 /// [dcl.fct.default].
1585  unsigned NumParams = FD->getNumParams();
1586  unsigned ParamIdx = 0;
1587 
1588  // This checking doesn't make sense for explicit specializations; their
1589  // default arguments are determined by the declaration we're specializing,
1590  // not by FD.
1592  return;
1593  if (auto *FTD = FD->getDescribedFunctionTemplate())
1594  if (FTD->isMemberSpecialization())
1595  return;
1596 
1597  // Find first parameter with a default argument
1598  for (; ParamIdx < NumParams; ++ParamIdx) {
1599  ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600  if (Param->hasDefaultArg())
1601  break;
1602  }
1603 
1604  // C++20 [dcl.fct.default]p4:
1605  // In a given function declaration, each parameter subsequent to a parameter
1606  // with a default argument shall have a default argument supplied in this or
1607  // a previous declaration, unless the parameter was expanded from a
1608  // parameter pack, or shall be a function parameter pack.
1609  for (; ParamIdx < NumParams; ++ParamIdx) {
1610  ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611  if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1614  if (Param->isInvalidDecl())
1615  /* We already complained about this parameter. */;
1616  else if (Param->getIdentifier())
1617  Diag(Param->getLocation(),
1618  diag::err_param_default_argument_missing_name)
1619  << Param->getIdentifier();
1620  else
1621  Diag(Param->getLocation(),
1622  diag::err_param_default_argument_missing);
1623  }
1624  }
1625 }
1626 
1627 /// Check that the given type is a literal type. Issue a diagnostic if not,
1628 /// if Kind is Diagnose.
1629 /// \return \c true if a problem has been found (and optionally diagnosed).
1630 template <typename... Ts>
1632  SourceLocation Loc, QualType T, unsigned DiagID,
1633  Ts &&...DiagArgs) {
1634  if (T->isDependentType())
1635  return false;
1636 
1637  switch (Kind) {
1639  return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640  std::forward<Ts>(DiagArgs)...);
1641 
1643  return !T->isLiteralType(SemaRef.Context);
1644  }
1645 
1646  llvm_unreachable("unknown CheckConstexprKind");
1647 }
1648 
1649 /// Determine whether a destructor cannot be constexpr due to
1651  const CXXDestructorDecl *DD,
1653  auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654  const CXXRecordDecl *RD =
1655  T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656  if (!RD || RD->hasConstexprDestructor())
1657  return true;
1658 
1660  SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661  << static_cast<int>(DD->getConstexprKind()) << !FD
1662  << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663  SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664  << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665  }
1666  return false;
1667  };
1668 
1669  const CXXRecordDecl *RD = DD->getParent();
1670  for (const CXXBaseSpecifier &B : RD->bases())
1671  if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672  return false;
1673  for (const FieldDecl *FD : RD->fields())
1674  if (!Check(FD->getLocation(), FD->getType(), FD))
1675  return false;
1676  return true;
1677 }
1678 
1679 /// Check whether a function's parameter types are all literal types. If so,
1680 /// return true. If not, produce a suitable diagnostic and return false.
1681 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682  const FunctionDecl *FD,
1684  unsigned ArgIndex = 0;
1685  const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686  for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687  e = FT->param_type_end();
1688  i != e; ++i, ++ArgIndex) {
1689  const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690  SourceLocation ParamLoc = PD->getLocation();
1691  if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692  diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693  PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694  FD->isConsteval()))
1695  return false;
1696  }
1697  return true;
1698 }
1699 
1700 /// Check whether a function's return type is a literal type. If so, return
1701 /// true. If not, produce a suitable diagnostic and return false.
1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1704  if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705  diag::err_constexpr_non_literal_return,
1706  FD->isConsteval()))
1707  return false;
1708  return true;
1709 }
1710 
1711 /// Get diagnostic %select index for tag kind for
1712 /// record diagnostic message.
1713 /// WARNING: Indexes apply to particular diagnostics only!
1714 ///
1715 /// \returns diagnostic %select index.
1717  switch (Tag) {
1718  case TTK_Struct: return 0;
1719  case TTK_Interface: return 1;
1720  case TTK_Class: return 2;
1721  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1722  }
1723 }
1724 
1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726  Stmt *Body,
1728 
1729 // Check whether a function declaration satisfies the requirements of a
1730 // constexpr function definition or a constexpr constructor definition. If so,
1731 // return true. If not, produce appropriate diagnostics (unless asked not to by
1732 // Kind) and return false.
1733 //
1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1737  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738  if (MD && MD->isInstance()) {
1739  // C++11 [dcl.constexpr]p4:
1740  // The definition of a constexpr constructor shall satisfy the following
1741  // constraints:
1742  // - the class shall not have any virtual base classes;
1743  //
1744  // FIXME: This only applies to constructors and destructors, not arbitrary
1745  // member functions.
1746  const CXXRecordDecl *RD = MD->getParent();
1747  if (RD->getNumVBases()) {
1749  return false;
1750 
1751  Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752  << isa<CXXConstructorDecl>(NewFD)
1754  for (const auto &I : RD->vbases())
1755  Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756  << I.getSourceRange();
1757  return false;
1758  }
1759  }
1760 
1761  if (!isa<CXXConstructorDecl>(NewFD)) {
1762  // C++11 [dcl.constexpr]p3:
1763  // The definition of a constexpr function shall satisfy the following
1764  // constraints:
1765  // - it shall not be virtual; (removed in C++20)
1766  const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767  if (Method && Method->isVirtual()) {
1768  if (getLangOpts().CPlusPlus20) {
1770  Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771  } else {
1773  return false;
1774 
1775  Method = Method->getCanonicalDecl();
1776  Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777 
1778  // If it's not obvious why this function is virtual, find an overridden
1779  // function which uses the 'virtual' keyword.
1780  const CXXMethodDecl *WrittenVirtual = Method;
1781  while (!WrittenVirtual->isVirtualAsWritten())
1782  WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783  if (WrittenVirtual != Method)
1784  Diag(WrittenVirtual->getLocation(),
1785  diag::note_overridden_virtual_function);
1786  return false;
1787  }
1788  }
1789 
1790  // - its return type shall be a literal type;
1791  if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792  return false;
1793  }
1794 
1795  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796  // A destructor can be constexpr only if the defaulted destructor could be;
1797  // we don't need to check the members and bases if we already know they all
1798  // have constexpr destructors.
1799  if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1801  return false;
1802  if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803  return false;
1804  }
1805  }
1806 
1807  // - each of its parameter types shall be a literal type;
1808  if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809  return false;
1810 
1811  Stmt *Body = NewFD->getBody();
1812  assert(Body &&
1813  "CheckConstexprFunctionDefinition called on function with no body");
1814  return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815 }
1816 
1817 /// Check the given declaration statement is legal within a constexpr function
1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819 ///
1820 /// \return true if the body is OK (maybe only as an extension), false if we
1821 /// have diagnosed a problem.
1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823  DeclStmt *DS, SourceLocation &Cxx1yLoc,
1825  // C++11 [dcl.constexpr]p3 and p4:
1826  // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827  // contain only
1828  for (const auto *DclIt : DS->decls()) {
1829  switch (DclIt->getKind()) {
1830  case Decl::StaticAssert:
1831  case Decl::Using:
1832  case Decl::UsingShadow:
1833  case Decl::UsingDirective:
1834  case Decl::UnresolvedUsingTypename:
1835  case Decl::UnresolvedUsingValue:
1836  case Decl::UsingEnum:
1837  // - static_assert-declarations
1838  // - using-declarations,
1839  // - using-directives,
1840  // - using-enum-declaration
1841  continue;
1842 
1843  case Decl::Typedef:
1844  case Decl::TypeAlias: {
1845  // - typedef declarations and alias-declarations that do not define
1846  // classes or enumerations,
1847  const auto *TN = cast<TypedefNameDecl>(DclIt);
1848  if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849  // Don't allow variably-modified types in constexpr functions.
1851  TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852  SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853  << TL.getSourceRange() << TL.getType()
1854  << isa<CXXConstructorDecl>(Dcl);
1855  }
1856  return false;
1857  }
1858  continue;
1859  }
1860 
1861  case Decl::Enum:
1862  case Decl::CXXRecord:
1863  // C++1y allows types to be defined, not just declared.
1864  if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1866  SemaRef.Diag(DS->getBeginLoc(),
1867  SemaRef.getLangOpts().CPlusPlus14
1868  ? diag::warn_cxx11_compat_constexpr_type_definition
1869  : diag::ext_constexpr_type_definition)
1870  << isa<CXXConstructorDecl>(Dcl);
1871  } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872  return false;
1873  }
1874  }
1875  continue;
1876 
1877  case Decl::EnumConstant:
1878  case Decl::IndirectField:
1879  case Decl::ParmVar:
1880  // These can only appear with other declarations which are banned in
1881  // C++11 and permitted in C++1y, so ignore them.
1882  continue;
1883 
1884  case Decl::Var:
1885  case Decl::Decomposition: {
1886  // C++1y [dcl.constexpr]p3 allows anything except:
1887  // a definition of a variable of non-literal type or of static or
1888  // thread storage duration or [before C++2a] for which no
1889  // initialization is performed.
1890  const auto *VD = cast<VarDecl>(DclIt);
1891  if (VD->isThisDeclarationADefinition()) {
1892  if (VD->isStaticLocal()) {
1894  SemaRef.Diag(VD->getLocation(),
1895  SemaRef.getLangOpts().CPlusPlus2b
1896  ? diag::warn_cxx20_compat_constexpr_static_var
1897  : diag::ext_constexpr_static_var)
1898  << isa<CXXConstructorDecl>(Dcl)
1899  << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1900  } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1901  return false;
1902  }
1903  }
1904  if (!SemaRef.LangOpts.CPlusPlus2b &&
1905  CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1906  diag::err_constexpr_local_var_non_literal_type,
1907  isa<CXXConstructorDecl>(Dcl)))
1908  return false;
1909  if (!VD->getType()->isDependentType() &&
1910  !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1912  SemaRef.Diag(
1913  VD->getLocation(),
1914  SemaRef.getLangOpts().CPlusPlus20
1915  ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1916  : diag::ext_constexpr_local_var_no_init)
1917  << isa<CXXConstructorDecl>(Dcl);
1918  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1919  return false;
1920  }
1921  continue;
1922  }
1923  }
1925  SemaRef.Diag(VD->getLocation(),
1926  SemaRef.getLangOpts().CPlusPlus14
1927  ? diag::warn_cxx11_compat_constexpr_local_var
1928  : diag::ext_constexpr_local_var)
1929  << isa<CXXConstructorDecl>(Dcl);
1930  } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1931  return false;
1932  }
1933  continue;
1934  }
1935 
1936  case Decl::NamespaceAlias:
1937  case Decl::Function:
1938  // These are disallowed in C++11 and permitted in C++1y. Allow them
1939  // everywhere as an extension.
1940  if (!Cxx1yLoc.isValid())
1941  Cxx1yLoc = DS->getBeginLoc();
1942  continue;
1943 
1944  default:
1946  SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1947  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1948  }
1949  return false;
1950  }
1951  }
1952 
1953  return true;
1954 }
1955 
1956 /// Check that the given field is initialized within a constexpr constructor.
1957 ///
1958 /// \param Dcl The constexpr constructor being checked.
1959 /// \param Field The field being checked. This may be a member of an anonymous
1960 /// struct or union nested within the class being checked.
1961 /// \param Inits All declarations, including anonymous struct/union members and
1962 /// indirect members, for which any initialization was provided.
1963 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1964 /// multiple notes for different members to the same error.
1965 /// \param Kind Whether we're diagnosing a constructor as written or determining
1966 /// whether the formal requirements are satisfied.
1967 /// \return \c false if we're checking for validity and the constructor does
1968 /// not satisfy the requirements on a constexpr constructor.
1970  const FunctionDecl *Dcl,
1971  FieldDecl *Field,
1972  llvm::SmallSet<Decl*, 16> &Inits,
1973  bool &Diagnosed,
1975  // In C++20 onwards, there's nothing to check for validity.
1977  SemaRef.getLangOpts().CPlusPlus20)
1978  return true;
1979 
1980  if (Field->isInvalidDecl())
1981  return true;
1982 
1983  if (Field->isUnnamedBitfield())
1984  return true;
1985 
1986  // Anonymous unions with no variant members and empty anonymous structs do not
1987  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1988  // indirect fields don't need initializing.
1989  if (Field->isAnonymousStructOrUnion() &&
1990  (Field->getType()->isUnionType()
1991  ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1992  : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1993  return true;
1994 
1995  if (!Inits.count(Field)) {
1997  if (!Diagnosed) {
1998  SemaRef.Diag(Dcl->getLocation(),
1999  SemaRef.getLangOpts().CPlusPlus20
2000  ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2001  : diag::ext_constexpr_ctor_missing_init);
2002  Diagnosed = true;
2003  }
2004  SemaRef.Diag(Field->getLocation(),
2005  diag::note_constexpr_ctor_missing_init);
2006  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2007  return false;
2008  }
2009  } else if (Field->isAnonymousStructOrUnion()) {
2010  const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2011  for (auto *I : RD->fields())
2012  // If an anonymous union contains an anonymous struct of which any member
2013  // is initialized, all members must be initialized.
2014  if (!RD->isUnion() || Inits.count(I))
2015  if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2016  Kind))
2017  return false;
2018  }
2019  return true;
2020 }
2021 
2022 /// Check the provided statement is allowed in a constexpr function
2023 /// definition.
2024 static bool
2026  SmallVectorImpl<SourceLocation> &ReturnStmts,
2027  SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2028  SourceLocation &Cxx2bLoc,
2030  // - its function-body shall be [...] a compound-statement that contains only
2031  switch (S->getStmtClass()) {
2032  case Stmt::NullStmtClass:
2033  // - null statements,
2034  return true;
2035 
2036  case Stmt::DeclStmtClass:
2037  // - static_assert-declarations
2038  // - using-declarations,
2039  // - using-directives,
2040  // - typedef declarations and alias-declarations that do not define
2041  // classes or enumerations,
2042  if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2043  return false;
2044  return true;
2045 
2046  case Stmt::ReturnStmtClass:
2047  // - and exactly one return statement;
2048  if (isa<CXXConstructorDecl>(Dcl)) {
2049  // C++1y allows return statements in constexpr constructors.
2050  if (!Cxx1yLoc.isValid())
2051  Cxx1yLoc = S->getBeginLoc();
2052  return true;
2053  }
2054 
2055  ReturnStmts.push_back(S->getBeginLoc());
2056  return true;
2057 
2058  case Stmt::AttributedStmtClass:
2059  // Attributes on a statement don't affect its formal kind and hence don't
2060  // affect its validity in a constexpr function.
2062  SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2063  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2064 
2065  case Stmt::CompoundStmtClass: {
2066  // C++1y allows compound-statements.
2067  if (!Cxx1yLoc.isValid())
2068  Cxx1yLoc = S->getBeginLoc();
2069 
2070  CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2071  for (auto *BodyIt : CompStmt->body()) {
2072  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2073  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2074  return false;
2075  }
2076  return true;
2077  }
2078 
2079  case Stmt::IfStmtClass: {
2080  // C++1y allows if-statements.
2081  if (!Cxx1yLoc.isValid())
2082  Cxx1yLoc = S->getBeginLoc();
2083 
2084  IfStmt *If = cast<IfStmt>(S);
2085  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2086  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2087  return false;
2088  if (If->getElse() &&
2089  !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2090  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2091  return false;
2092  return true;
2093  }
2094 
2095  case Stmt::WhileStmtClass:
2096  case Stmt::DoStmtClass:
2097  case Stmt::ForStmtClass:
2098  case Stmt::CXXForRangeStmtClass:
2099  case Stmt::ContinueStmtClass:
2100  // C++1y allows all of these. We don't allow them as extensions in C++11,
2101  // because they don't make sense without variable mutation.
2102  if (!SemaRef.getLangOpts().CPlusPlus14)
2103  break;
2104  if (!Cxx1yLoc.isValid())
2105  Cxx1yLoc = S->getBeginLoc();
2106  for (Stmt *SubStmt : S->children()) {
2107  if (SubStmt &&
2108  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2109  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2110  return false;
2111  }
2112  return true;
2113 
2114  case Stmt::SwitchStmtClass:
2115  case Stmt::CaseStmtClass:
2116  case Stmt::DefaultStmtClass:
2117  case Stmt::BreakStmtClass:
2118  // C++1y allows switch-statements, and since they don't need variable
2119  // mutation, we can reasonably allow them in C++11 as an extension.
2120  if (!Cxx1yLoc.isValid())
2121  Cxx1yLoc = S->getBeginLoc();
2122  for (Stmt *SubStmt : S->children()) {
2123  if (SubStmt &&
2124  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2125  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2126  return false;
2127  }
2128  return true;
2129 
2130  case Stmt::LabelStmtClass:
2131  case Stmt::GotoStmtClass:
2132  if (Cxx2bLoc.isInvalid())
2133  Cxx2bLoc = S->getBeginLoc();
2134  for (Stmt *SubStmt : S->children()) {
2135  if (SubStmt &&
2136  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2137  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2138  return false;
2139  }
2140  return true;
2141 
2142  case Stmt::GCCAsmStmtClass:
2143  case Stmt::MSAsmStmtClass:
2144  // C++2a allows inline assembly statements.
2145  case Stmt::CXXTryStmtClass:
2146  if (Cxx2aLoc.isInvalid())
2147  Cxx2aLoc = S->getBeginLoc();
2148  for (Stmt *SubStmt : S->children()) {
2149  if (SubStmt &&
2150  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2151  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2152  return false;
2153  }
2154  return true;
2155 
2156  case Stmt::CXXCatchStmtClass:
2157  // Do not bother checking the language mode (already covered by the
2158  // try block check).
2160  SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2161  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2162  return false;
2163  return true;
2164 
2165  default:
2166  if (!isa<Expr>(S))
2167  break;
2168 
2169  // C++1y allows expression-statements.
2170  if (!Cxx1yLoc.isValid())
2171  Cxx1yLoc = S->getBeginLoc();
2172  return true;
2173  }
2174 
2176  SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2177  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2178  }
2179  return false;
2180 }
2181 
2182 /// Check the body for the given constexpr function declaration only contains
2183 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2184 ///
2185 /// \return true if the body is OK, false if we have found or diagnosed a
2186 /// problem.
2187 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2188  Stmt *Body,
2190  SmallVector<SourceLocation, 4> ReturnStmts;
2191 
2192  if (isa<CXXTryStmt>(Body)) {
2193  // C++11 [dcl.constexpr]p3:
2194  // The definition of a constexpr function shall satisfy the following
2195  // constraints: [...]
2196  // - its function-body shall be = delete, = default, or a
2197  // compound-statement
2198  //
2199  // C++11 [dcl.constexpr]p4:
2200  // In the definition of a constexpr constructor, [...]
2201  // - its function-body shall not be a function-try-block;
2202  //
2203  // This restriction is lifted in C++2a, as long as inner statements also
2204  // apply the general constexpr rules.
2205  switch (Kind) {
2207  if (!SemaRef.getLangOpts().CPlusPlus20)
2208  return false;
2209  break;
2210 
2212  SemaRef.Diag(Body->getBeginLoc(),
2213  !SemaRef.getLangOpts().CPlusPlus20
2214  ? diag::ext_constexpr_function_try_block_cxx20
2215  : diag::warn_cxx17_compat_constexpr_function_try_block)
2216  << isa<CXXConstructorDecl>(Dcl);
2217  break;
2218  }
2219  }
2220 
2221  // - its function-body shall be [...] a compound-statement that contains only
2222  // [... list of cases ...]
2223  //
2224  // Note that walking the children here is enough to properly check for
2225  // CompoundStmt and CXXTryStmt body.
2226  SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2227  for (Stmt *SubStmt : Body->children()) {
2228  if (SubStmt &&
2229  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2230  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2231  return false;
2232  }
2233 
2235  // If this is only valid as an extension, report that we don't satisfy the
2236  // constraints of the current language.
2237  if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2238  (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2239  (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2240  return false;
2241  } else if (Cxx2bLoc.isValid()) {
2242  SemaRef.Diag(Cxx2bLoc,
2243  SemaRef.getLangOpts().CPlusPlus2b
2244  ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2245  : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2246  << isa<CXXConstructorDecl>(Dcl);
2247  } else if (Cxx2aLoc.isValid()) {
2248  SemaRef.Diag(Cxx2aLoc,
2249  SemaRef.getLangOpts().CPlusPlus20
2250  ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2251  : diag::ext_constexpr_body_invalid_stmt_cxx20)
2252  << isa<CXXConstructorDecl>(Dcl);
2253  } else if (Cxx1yLoc.isValid()) {
2254  SemaRef.Diag(Cxx1yLoc,
2255  SemaRef.getLangOpts().CPlusPlus14
2256  ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2257  : diag::ext_constexpr_body_invalid_stmt)
2258  << isa<CXXConstructorDecl>(Dcl);
2259  }
2260 
2261  if (const CXXConstructorDecl *Constructor
2262  = dyn_cast<CXXConstructorDecl>(Dcl)) {
2263  const CXXRecordDecl *RD = Constructor->getParent();
2264  // DR1359:
2265  // - every non-variant non-static data member and base class sub-object
2266  // shall be initialized;
2267  // DR1460:
2268  // - if the class is a union having variant members, exactly one of them
2269  // shall be initialized;
2270  if (RD->isUnion()) {
2271  if (Constructor->getNumCtorInitializers() == 0 &&
2272  RD->hasVariantMembers()) {
2274  SemaRef.Diag(
2275  Dcl->getLocation(),
2276  SemaRef.getLangOpts().CPlusPlus20
2277  ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2278  : diag::ext_constexpr_union_ctor_no_init);
2279  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2280  return false;
2281  }
2282  }
2283  } else if (!Constructor->isDependentContext() &&
2284  !Constructor->isDelegatingConstructor()) {
2285  assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2286 
2287  // Skip detailed checking if we have enough initializers, and we would
2288  // allow at most one initializer per member.
2289  bool AnyAnonStructUnionMembers = false;
2290  unsigned Fields = 0;
2292  E = RD->field_end(); I != E; ++I, ++Fields) {
2293  if (I->isAnonymousStructOrUnion()) {
2294  AnyAnonStructUnionMembers = true;
2295  break;
2296  }
2297  }
2298  // DR1460:
2299  // - if the class is a union-like class, but is not a union, for each of
2300  // its anonymous union members having variant members, exactly one of
2301  // them shall be initialized;
2302  if (AnyAnonStructUnionMembers ||
2303  Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2304  // Check initialization of non-static data members. Base classes are
2305  // always initialized so do not need to be checked. Dependent bases
2306  // might not have initializers in the member initializer list.
2307  llvm::SmallSet<Decl*, 16> Inits;
2308  for (const auto *I: Constructor->inits()) {
2309  if (FieldDecl *FD = I->getMember())
2310  Inits.insert(FD);
2311  else if (IndirectFieldDecl *ID = I->getIndirectMember())
2312  Inits.insert(ID->chain_begin(), ID->chain_end());
2313  }
2314 
2315  bool Diagnosed = false;
2316  for (auto *I : RD->fields())
2317  if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2318  Kind))
2319  return false;
2320  }
2321  }
2322  } else {
2323  if (ReturnStmts.empty()) {
2324  // C++1y doesn't require constexpr functions to contain a 'return'
2325  // statement. We still do, unless the return type might be void, because
2326  // otherwise if there's no return statement, the function cannot
2327  // be used in a core constant expression.
2328  bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2329  (Dcl->getReturnType()->isVoidType() ||
2330  Dcl->getReturnType()->isDependentType());
2331  switch (Kind) {
2333  SemaRef.Diag(Dcl->getLocation(),
2334  OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2335  : diag::err_constexpr_body_no_return)
2336  << Dcl->isConsteval();
2337  if (!OK)
2338  return false;
2339  break;
2340 
2342  // The formal requirements don't include this rule in C++14, even
2343  // though the "must be able to produce a constant expression" rules
2344  // still imply it in some cases.
2345  if (!SemaRef.getLangOpts().CPlusPlus14)
2346  return false;
2347  break;
2348  }
2349  } else if (ReturnStmts.size() > 1) {
2350  switch (Kind) {
2352  SemaRef.Diag(
2353  ReturnStmts.back(),
2354  SemaRef.getLangOpts().CPlusPlus14
2355  ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2356  : diag::ext_constexpr_body_multiple_return);
2357  for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2358  SemaRef.Diag(ReturnStmts[I],
2359  diag::note_constexpr_body_previous_return);
2360  break;
2361 
2363  if (!SemaRef.getLangOpts().CPlusPlus14)
2364  return false;
2365  break;
2366  }
2367  }
2368  }
2369 
2370  // C++11 [dcl.constexpr]p5:
2371  // if no function argument values exist such that the function invocation
2372  // substitution would produce a constant expression, the program is
2373  // ill-formed; no diagnostic required.
2374  // C++11 [dcl.constexpr]p3:
2375  // - every constructor call and implicit conversion used in initializing the
2376  // return value shall be one of those allowed in a constant expression.
2377  // C++11 [dcl.constexpr]p4:
2378  // - every constructor involved in initializing non-static data members and
2379  // base class sub-objects shall be a constexpr constructor.
2380  //
2381  // Note that this rule is distinct from the "requirements for a constexpr
2382  // function", so is not checked in CheckValid mode.
2386  SemaRef.Diag(Dcl->getLocation(),
2387  diag::ext_constexpr_function_never_constant_expr)
2388  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2389  for (size_t I = 0, N = Diags.size(); I != N; ++I)
2390  SemaRef.Diag(Diags[I].first, Diags[I].second);
2391  // Don't return false here: we allow this for compatibility in
2392  // system headers.
2393  }
2394 
2395  return true;
2396 }
2397 
2398 /// Get the class that is directly named by the current context. This is the
2399 /// class for which an unqualified-id in this scope could name a constructor
2400 /// or destructor.
2401 ///
2402 /// If the scope specifier denotes a class, this will be that class.
2403 /// If the scope specifier is empty, this will be the class whose
2404 /// member-specification we are currently within. Otherwise, there
2405 /// is no such class.
2407  assert(getLangOpts().CPlusPlus && "No class names in C!");
2408 
2409  if (SS && SS->isInvalid())
2410  return nullptr;
2411 
2412  if (SS && SS->isNotEmpty()) {
2413  DeclContext *DC = computeDeclContext(*SS, true);
2414  return dyn_cast_or_null<CXXRecordDecl>(DC);
2415  }
2416 
2417  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2418 }
2419 
2420 /// isCurrentClassName - Determine whether the identifier II is the
2421 /// name of the class type currently being defined. In the case of
2422 /// nested classes, this will only return true if II is the name of
2423 /// the innermost class.
2425  const CXXScopeSpec *SS) {
2426  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2427  return CurDecl && &II == CurDecl->getIdentifier();
2428 }
2429 
2430 /// Determine whether the identifier II is a typo for the name of
2431 /// the class type currently being defined. If so, update it to the identifier
2432 /// that should have been used.
2434  assert(getLangOpts().CPlusPlus && "No class names in C!");
2435 
2436  if (!getLangOpts().SpellChecking)
2437  return false;
2438 
2439  CXXRecordDecl *CurDecl;
2440  if (SS && SS->isSet() && !SS->isInvalid()) {
2441  DeclContext *DC = computeDeclContext(*SS, true);
2442  CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2443  } else
2444  CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2445 
2446  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2447  3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2448  < II->getLength()) {
2449  II = CurDecl->getIdentifier();
2450  return true;
2451  }
2452 
2453  return false;
2454 }
2455 
2456 /// Determine whether the given class is a base class of the given
2457 /// class, including looking at dependent bases.
2458 static bool findCircularInheritance(const CXXRecordDecl *Class,
2459  const CXXRecordDecl *Current) {
2461 
2462  Class = Class->getCanonicalDecl();
2463  while (true) {
2464  for (const auto &I : Current->bases()) {
2465  CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2466  if (!Base)
2467  continue;
2468 
2469  Base = Base->getDefinition();
2470  if (!Base)
2471  continue;
2472 
2473  if (Base->getCanonicalDecl() == Class)
2474  return true;
2475 
2476  Queue.push_back(Base);
2477  }
2478 
2479  if (Queue.empty())
2480  return false;
2481 
2482  Current = Queue.pop_back_val();
2483  }
2484 
2485  return false;
2486 }
2487 
2488 /// Check the validity of a C++ base class specifier.
2489 ///
2490 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2491 /// and returns NULL otherwise.
2494  SourceRange SpecifierRange,
2495  bool Virtual, AccessSpecifier Access,
2496  TypeSourceInfo *TInfo,
2497  SourceLocation EllipsisLoc) {
2498  QualType BaseType = TInfo->getType();
2499  if (BaseType->containsErrors()) {
2500  // Already emitted a diagnostic when parsing the error type.
2501  return nullptr;
2502  }
2503  // C++ [class.union]p1:
2504  // A union shall not have base classes.
2505  if (Class->isUnion()) {
2506  Diag(Class->getLocation(), diag::err_base_clause_on_union)
2507  << SpecifierRange;
2508  return nullptr;
2509  }
2510 
2511  if (EllipsisLoc.isValid() &&
2513  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2514  << TInfo->getTypeLoc().getSourceRange();
2515  EllipsisLoc = SourceLocation();
2516  }
2517 
2518  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2519 
2520  if (BaseType->isDependentType()) {
2521  // Make sure that we don't have circular inheritance among our dependent
2522  // bases. For non-dependent bases, the check for completeness below handles
2523  // this.
2524  if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2525  if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2526  ((BaseDecl = BaseDecl->getDefinition()) &&
2527  findCircularInheritance(Class, BaseDecl))) {
2528  Diag(BaseLoc, diag::err_circular_inheritance)
2529  << BaseType << Context.getTypeDeclType(Class);
2530 
2531  if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2532  Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2533  << BaseType;
2534 
2535  return nullptr;
2536  }
2537  }
2538 
2539  // Make sure that we don't make an ill-formed AST where the type of the
2540  // Class is non-dependent and its attached base class specifier is an
2541  // dependent type, which violates invariants in many clang code paths (e.g.
2542  // constexpr evaluator). If this case happens (in errory-recovery mode), we
2543  // explicitly mark the Class decl invalid. The diagnostic was already
2544  // emitted.
2545  if (!Class->getTypeForDecl()->isDependentType())
2546  Class->setInvalidDecl();
2547  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2548  Class->getTagKind() == TTK_Class,
2549  Access, TInfo, EllipsisLoc);
2550  }
2551 
2552  // Base specifiers must be record types.
2553  if (!BaseType->isRecordType()) {
2554  Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2555  return nullptr;
2556  }
2557 
2558  // C++ [class.union]p1:
2559  // A union shall not be used as a base class.
2560  if (BaseType->isUnionType()) {
2561  Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2562  return nullptr;
2563  }
2564 
2565  // For the MS ABI, propagate DLL attributes to base class templates.
2567  if (Attr *ClassAttr = getDLLAttr(Class)) {
2568  if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2569  BaseType->getAsCXXRecordDecl())) {
2570  propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2571  BaseLoc);
2572  }
2573  }
2574  }
2575 
2576  // C++ [class.derived]p2:
2577  // The class-name in a base-specifier shall not be an incompletely
2578  // defined class.
2579  if (RequireCompleteType(BaseLoc, BaseType,
2580  diag::err_incomplete_base_class, SpecifierRange)) {
2581  Class->setInvalidDecl();
2582  return nullptr;
2583  }
2584 
2585  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2586  RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2587  assert(BaseDecl && "Record type has no declaration");
2588  BaseDecl = BaseDecl->getDefinition();
2589  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2590  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2591  assert(CXXBaseDecl && "Base type is not a C++ type");
2592 
2593  // Microsoft docs say:
2594  // "If a base-class has a code_seg attribute, derived classes must have the
2595  // same attribute."
2596  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2597  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2598  if ((DerivedCSA || BaseCSA) &&
2599  (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2600  Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2601  Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2602  << CXXBaseDecl;
2603  return nullptr;
2604  }
2605 
2606  // A class which contains a flexible array member is not suitable for use as a
2607  // base class:
2608  // - If the layout determines that a base comes before another base,
2609  // the flexible array member would index into the subsequent base.
2610  // - If the layout determines that base comes before the derived class,
2611  // the flexible array member would index into the derived class.
2612  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2613  Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2614  << CXXBaseDecl->getDeclName();
2615  return nullptr;
2616  }
2617 
2618  // C++ [class]p3:
2619  // If a class is marked final and it appears as a base-type-specifier in
2620  // base-clause, the program is ill-formed.
2621  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2622  Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2623  << CXXBaseDecl->getDeclName()
2624  << FA->isSpelledAsSealed();
2625  Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2626  << CXXBaseDecl->getDeclName() << FA->getRange();
2627  return nullptr;
2628  }
2629 
2630  if (BaseDecl->isInvalidDecl())
2631  Class->setInvalidDecl();
2632 
2633  // Create the base specifier.
2634  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2635  Class->getTagKind() == TTK_Class,
2636  Access, TInfo, EllipsisLoc);
2637 }
2638 
2639 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2640 /// one entry in the base class list of a class specifier, for
2641 /// example:
2642 /// class foo : public bar, virtual private baz {
2643 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2645  const ParsedAttributesView &Attributes,
2646  bool Virtual, AccessSpecifier Access,
2647  ParsedType basetype, SourceLocation BaseLoc,
2648  SourceLocation EllipsisLoc) {
2649  if (!classdecl)
2650  return true;
2651 
2652  AdjustDeclIfTemplate(classdecl);
2653  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2654  if (!Class)
2655  return true;
2656 
2657  // We haven't yet attached the base specifiers.
2658  Class->setIsParsingBaseSpecifiers();
2659 
2660  // We do not support any C++11 attributes on base-specifiers yet.
2661  // Diagnose any attributes we see.
2662  for (const ParsedAttr &AL : Attributes) {
2663  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2664  continue;
2665  Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2666  ? (unsigned)diag::warn_unknown_attribute_ignored
2667  : (unsigned)diag::err_base_specifier_attribute)
2668  << AL << AL.getRange();
2669  }
2670 
2671  TypeSourceInfo *TInfo = nullptr;
2672  GetTypeFromParser(basetype, &TInfo);
2673 
2674  if (EllipsisLoc.isInvalid() &&
2675  DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2676  UPPC_BaseType))
2677  return true;
2678 
2679  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2680  Virtual, Access, TInfo,
2681  EllipsisLoc))
2682  return BaseSpec;
2683  else
2684  Class->setInvalidDecl();
2685 
2686  return true;
2687 }
2688 
2689 /// Use small set to collect indirect bases. As this is only used
2690 /// locally, there's no need to abstract the small size parameter.
2692 
2693 /// Recursively add the bases of Type. Don't add Type itself.
2694 static void
2696  const QualType &Type)
2697 {
2698  // Even though the incoming type is a base, it might not be
2699  // a class -- it could be a template parm, for instance.
2700  if (auto Rec = Type->getAs<RecordType>()) {
2701  auto Decl = Rec->getAsCXXRecordDecl();
2702 
2703  // Iterate over its bases.
2704  for (const auto &BaseSpec : Decl->bases()) {
2705  QualType Base = Context.getCanonicalType(BaseSpec.getType())
2706  .getUnqualifiedType();
2707  if (Set.insert(Base).second)
2708  // If we've not already seen it, recurse.
2710  }
2711  }
2712 }
2713 
2714 /// Performs the actual work of attaching the given base class
2715 /// specifiers to a C++ class.
2718  if (Bases.empty())
2719  return false;
2720 
2721  // Used to keep track of which base types we have already seen, so
2722  // that we can properly diagnose redundant direct base types. Note
2723  // that the key is always the unqualified canonical type of the base
2724  // class.
2725  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2726 
2727  // Used to track indirect bases so we can see if a direct base is
2728  // ambiguous.
2729  IndirectBaseSet IndirectBaseTypes;
2730 
2731  // Copy non-redundant base specifiers into permanent storage.
2732  unsigned NumGoodBases = 0;
2733  bool Invalid = false;
2734  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2735  QualType NewBaseType
2736  = Context.getCanonicalType(Bases[idx]->getType());
2737  NewBaseType = NewBaseType.getLocalUnqualifiedType();
2738 
2739  CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2740  if (KnownBase) {
2741  // C++ [class.mi]p3:
2742  // A class shall not be specified as a direct base class of a
2743  // derived class more than once.
2744  Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2745  << KnownBase->getType() << Bases[idx]->getSourceRange();
2746 
2747  // Delete the duplicate base class specifier; we're going to
2748  // overwrite its pointer later.
2749  Context.Deallocate(Bases[idx]);
2750 
2751  Invalid = true;
2752  } else {
2753  // Okay, add this new base class.
2754  KnownBase = Bases[idx];
2755  Bases[NumGoodBases++] = Bases[idx];
2756 
2757  if (NewBaseType->isDependentType())
2758  continue;
2759  // Note this base's direct & indirect bases, if there could be ambiguity.
2760  if (Bases.size() > 1)
2761  NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2762 
2763  if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2764  const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2765  if (Class->isInterface() &&
2766  (!RD->isInterfaceLike() ||
2767  KnownBase->getAccessSpecifier() != AS_public)) {
2768  // The Microsoft extension __interface does not permit bases that
2769  // are not themselves public interfaces.
2770  Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2771  << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2772  << RD->getSourceRange();
2773  Invalid = true;
2774  }
2775  if (RD->hasAttr<WeakAttr>())
2776  Class->addAttr(WeakAttr::CreateImplicit(Context));
2777  }
2778  }
2779  }
2780 
2781  // Attach the remaining base class specifiers to the derived class.
2782  Class->setBases(Bases.data(), NumGoodBases);
2783 
2784  // Check that the only base classes that are duplicate are virtual.
2785  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2786  // Check whether this direct base is inaccessible due to ambiguity.
2787  QualType BaseType = Bases[idx]->getType();
2788 
2789  // Skip all dependent types in templates being used as base specifiers.
2790  // Checks below assume that the base specifier is a CXXRecord.
2791  if (BaseType->isDependentType())
2792  continue;
2793 
2794  CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2795  .getUnqualifiedType();
2796 
2797  if (IndirectBaseTypes.count(CanonicalBase)) {
2798  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2799  /*DetectVirtual=*/true);
2800  bool found
2801  = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2802  assert(found);
2803  (void)found;
2804 
2805  if (Paths.isAmbiguous(CanonicalBase))
2806  Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2807  << BaseType << getAmbiguousPathsDisplayString(Paths)
2808  << Bases[idx]->getSourceRange();
2809  else
2810  assert(Bases[idx]->isVirtual());
2811  }
2812 
2813  // Delete the base class specifier, since its data has been copied
2814  // into the CXXRecordDecl.
2815  Context.Deallocate(Bases[idx]);
2816  }
2817 
2818  return Invalid;
2819 }
2820 
2821 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2822 /// class, after checking whether there are any duplicate base
2823 /// classes.
2826  if (!ClassDecl || Bases.empty())
2827  return;
2828 
2829  AdjustDeclIfTemplate(ClassDecl);
2830  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2831 }
2832 
2833 /// Determine whether the type \p Derived is a C++ class that is
2834 /// derived from the type \p Base.
2836  if (!getLangOpts().CPlusPlus)
2837  return false;
2838 
2839  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2840  if (!DerivedRD)
2841  return false;
2842 
2843  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2844  if (!BaseRD)
2845  return false;
2846 
2847  // If either the base or the derived type is invalid, don't try to
2848  // check whether one is derived from the other.
2849  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2850  return false;
2851 
2852  // FIXME: In a modules build, do we need the entire path to be visible for us
2853  // to be able to use the inheritance relationship?
2854  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2855  return false;
2856 
2857  return DerivedRD->isDerivedFrom(BaseRD);
2858 }
2859 
2860 /// Determine whether the type \p Derived is a C++ class that is
2861 /// derived from the type \p Base.
2863  CXXBasePaths &Paths) {
2864  if (!getLangOpts().CPlusPlus)
2865  return false;
2866 
2867  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2868  if (!DerivedRD)
2869  return false;
2870 
2871  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2872  if (!BaseRD)
2873  return false;
2874 
2875  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2876  return false;
2877 
2878  return DerivedRD->isDerivedFrom(BaseRD, Paths);
2879 }
2880 
2881 static void BuildBasePathArray(const CXXBasePath &Path,
2882  CXXCastPath &BasePathArray) {
2883  // We first go backward and check if we have a virtual base.
2884  // FIXME: It would be better if CXXBasePath had the base specifier for
2885  // the nearest virtual base.
2886  unsigned Start = 0;
2887  for (unsigned I = Path.size(); I != 0; --I) {
2888  if (Path[I - 1].Base->isVirtual()) {
2889  Start = I - 1;
2890  break;
2891  }
2892  }
2893 
2894  // Now add all bases.
2895  for (unsigned I = Start, E = Path.size(); I != E; ++I)
2896  BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2897 }
2898 
2899 
2901  CXXCastPath &BasePathArray) {
2902  assert(BasePathArray.empty() && "Base path array must be empty!");
2903  assert(Paths.isRecordingPaths() && "Must record paths!");
2904  return ::BuildBasePathArray(Paths.front(), BasePathArray);
2905 }
2906 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2907 /// conversion (where Derived and Base are class types) is
2908 /// well-formed, meaning that the conversion is unambiguous (and
2909 /// that all of the base classes are accessible). Returns true
2910 /// and emits a diagnostic if the code is ill-formed, returns false
2911 /// otherwise. Loc is the location where this routine should point to
2912 /// if there is an error, and Range is the source range to highlight
2913 /// if there is an error.
2914 ///
2915 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2916 /// diagnostic for the respective type of error will be suppressed, but the
2917 /// check for ill-formed code will still be performed.
2918 bool
2920  unsigned InaccessibleBaseID,
2921  unsigned AmbiguousBaseConvID,
2922  SourceLocation Loc, SourceRange Range,
2923  DeclarationName Name,
2924  CXXCastPath *BasePath,
2925  bool IgnoreAccess) {
2926  // First, determine whether the path from Derived to Base is
2927  // ambiguous. This is slightly more expensive than checking whether
2928  // the Derived to Base conversion exists, because here we need to
2929  // explore multiple paths to determine if there is an ambiguity.
2930  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2931  /*DetectVirtual=*/false);
2932  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2933  if (!DerivationOkay)
2934  return true;
2935 
2936  const CXXBasePath *Path = nullptr;
2937  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2938  Path = &Paths.front();
2939 
2940  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2941  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2942  // user to access such bases.
2943  if (!Path && getLangOpts().MSVCCompat) {
2944  for (const CXXBasePath &PossiblePath : Paths) {
2945  if (PossiblePath.size() == 1) {
2946  Path = &PossiblePath;
2947  if (AmbiguousBaseConvID)
2948  Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2949  << Base << Derived << Range;
2950  break;
2951  }
2952  }
2953  }
2954 
2955  if (Path) {
2956  if (!IgnoreAccess) {
2957  // Check that the base class can be accessed.
2958  switch (
2959  CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2960  case AR_inaccessible:
2961  return true;
2962  case AR_accessible:
2963  case AR_dependent:
2964  case AR_delayed:
2965  break;
2966  }
2967  }
2968 
2969  // Build a base path if necessary.
2970  if (BasePath)
2971  ::BuildBasePathArray(*Path, *BasePath);
2972  return false;
2973  }
2974 
2975  if (AmbiguousBaseConvID) {
2976  // We know that the derived-to-base conversion is ambiguous, and
2977  // we're going to produce a diagnostic. Perform the derived-to-base
2978  // search just one more time to compute all of the possible paths so
2979  // that we can print them out. This is more expensive than any of
2980  // the previous derived-to-base checks we've done, but at this point
2981  // performance isn't as much of an issue.
2982  Paths.clear();
2983  Paths.setRecordingPaths(true);
2984  bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2985  assert(StillOkay && "Can only be used with a derived-to-base conversion");
2986  (void)StillOkay;
2987 
2988  // Build up a textual representation of the ambiguous paths, e.g.,
2989  // D -> B -> A, that will be used to illustrate the ambiguous
2990  // conversions in the diagnostic. We only print one of the paths
2991  // to each base class subobject.
2992  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2993 
2994  Diag(Loc, AmbiguousBaseConvID)
2995  << Derived << Base << PathDisplayStr << Range << Name;
2996  }
2997  return true;
2998 }
2999 
3000 bool
3002  SourceLocation Loc, SourceRange Range,
3003  CXXCastPath *BasePath,
3004  bool IgnoreAccess) {
3006  Derived, Base, diag::err_upcast_to_inaccessible_base,
3007  diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3008  BasePath, IgnoreAccess);
3009 }
3010 
3011 
3012 /// Builds a string representing ambiguous paths from a
3013 /// specific derived class to different subobjects of the same base
3014 /// class.
3015 ///
3016 /// This function builds a string that can be used in error messages
3017 /// to show the different paths that one can take through the
3018 /// inheritance hierarchy to go from the derived class to different
3019 /// subobjects of a base class. The result looks something like this:
3020 /// @code
3021 /// struct D -> struct B -> struct A
3022 /// struct D -> struct C -> struct A
3023 /// @endcode
3025  std::string PathDisplayStr;
3026  std::set<unsigned> DisplayedPaths;
3027  for (CXXBasePaths::paths_iterator Path = Paths.begin();
3028  Path != Paths.end(); ++Path) {
3029  if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3030  // We haven't displayed a path to this particular base
3031  // class subobject yet.
3032  PathDisplayStr += "\n ";
3033  PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3034  for (CXXBasePath::const_iterator Element = Path->begin();
3035  Element != Path->end(); ++Element)
3036  PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3037  }
3038  }
3039 
3040  return PathDisplayStr;
3041 }
3042 
3043 //===----------------------------------------------------------------------===//
3044 // C++ class member Handling
3045 //===----------------------------------------------------------------------===//
3046 
3047 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3049  SourceLocation ColonLoc,
3050  const ParsedAttributesView &Attrs) {
3051  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3053  ASLoc, ColonLoc);
3054  CurContext->addHiddenDecl(ASDecl);
3055  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3056 }
3057 
3058 /// CheckOverrideControl - Check C++11 override control semantics.
3060  if (D->isInvalidDecl())
3061  return;
3062 
3063  // We only care about "override" and "final" declarations.
3064  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3065  return;
3066 
3067  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3068 
3069  // We can't check dependent instance methods.
3070  if (MD && MD->isInstance() &&
3071  (MD->getParent()->hasAnyDependentBases() ||
3072  MD->getType()->isDependentType()))
3073  return;
3074 
3075  if (MD && !MD->isVirtual()) {
3076  // If we have a non-virtual method, check if if hides a virtual method.
3077  // (In that case, it's most likely the method has the wrong type.)
3078  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3079  FindHiddenVirtualMethods(MD, OverloadedMethods);
3080 
3081  if (!OverloadedMethods.empty()) {
3082  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3083  Diag(OA->getLocation(),
3084  diag::override_keyword_hides_virtual_member_function)
3085  << "override" << (OverloadedMethods.size() > 1);
3086  } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3087  Diag(FA->getLocation(),
3088  diag::override_keyword_hides_virtual_member_function)
3089  << (FA->isSpelledAsSealed() ? "sealed" : "final")
3090  << (OverloadedMethods.size() > 1);
3091  }
3092  NoteHiddenVirtualMethods(MD, OverloadedMethods);
3093  MD->setInvalidDecl();
3094  return;
3095  }
3096  // Fall through into the general case diagnostic.
3097  // FIXME: We might want to attempt typo correction here.
3098  }
3099 
3100  if (!MD || !MD->isVirtual()) {
3101  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3102  Diag(OA->getLocation(),
3103  diag::override_keyword_only_allowed_on_virtual_member_functions)
3104  << "override" << FixItHint::CreateRemoval(OA->getLocation());
3105  D->dropAttr<OverrideAttr>();
3106  }
3107  if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3108  Diag(FA->getLocation(),
3109  diag::override_keyword_only_allowed_on_virtual_member_functions)
3110  << (FA->isSpelledAsSealed() ? "sealed" : "final")
3111  << FixItHint::CreateRemoval(FA->getLocation());
3112  D->dropAttr<FinalAttr>();
3113  }
3114  return;
3115  }
3116 
3117  // C++11 [class.virtual]p5:
3118  // If a function is marked with the virt-specifier override and
3119  // does not override a member function of a base class, the program is
3120  // ill-formed.
3121  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3122  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3123  Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3124  << MD->getDeclName();
3125 }
3126 
3127 // Check and diagnose if a SYCLAddIRAttributesFunctionAttr is attached to a
3128 // virtual member function.
3130  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3131  if (!MD)
3132  return;
3133 
3134  // sycl_add_ir_attributes_function is not currently allowed on virtual member
3135  // functions.
3136  if (const auto *AddIRAttr = MD->getAttr<SYCLAddIRAttributesFunctionAttr>()) {
3137  if (MD->isVirtual()) {
3138  Diag(AddIRAttr->getLoc(), diag::err_disallow_attribute_on_func)
3139  << AddIRAttr << 0;
3140  return;
3141  }
3142  }
3143 }
3144 
3146  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3147  return;
3148  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3149  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3150  return;
3151 
3152  SourceLocation Loc = MD->getLocation();
3153  SourceLocation SpellingLoc = Loc;
3154  if (getSourceManager().isMacroArgExpansion(Loc))
3155  SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3156  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3157  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3158  return;
3159 
3160  if (MD->size_overridden_methods() > 0) {
3161  auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3162  unsigned DiagID =
3163  Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3164  ? DiagInconsistent
3165  : DiagSuggest;
3166  Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3167  const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3168  Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3169  };
3170  if (isa<CXXDestructorDecl>(MD))
3171  EmitDiag(
3172  diag::warn_inconsistent_destructor_marked_not_override_overriding,
3173  diag::warn_suggest_destructor_marked_not_override_overriding);
3174  else
3175  EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3176  diag::warn_suggest_function_marked_not_override_overriding);
3177  }
3178 }
3179 
3180 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3181 /// function overrides a virtual member function marked 'final', according to
3182 /// C++11 [class.virtual]p4.
3184  const CXXMethodDecl *Old) {
3185  FinalAttr *FA = Old->getAttr<FinalAttr>();
3186  if (!FA)
3187  return false;
3188 
3189  Diag(New->getLocation(), diag::err_final_function_overridden)
3190  << New->getDeclName()
3191  << FA->isSpelledAsSealed();
3192  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3193  return true;
3194 }
3195 
3196 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3197  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3198  // FIXME: Destruction of ObjC lifetime types has side-effects.
3199  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3200  return !RD->isCompleteDefinition() ||
3201  !RD->hasTrivialDefaultConstructor() ||
3202  !RD->hasTrivialDestructor();
3203  return false;
3204 }
3205 
3208  llvm::find_if(list, [](const ParsedAttr &AL) {
3209  return AL.isDeclspecPropertyAttribute();
3210  });
3211  if (Itr != list.end())
3212  return &*Itr;
3213  return nullptr;
3214 }
3215 
3216 // Check if there is a field shadowing.
3217 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3218  DeclarationName FieldName,
3219  const CXXRecordDecl *RD,
3220  bool DeclIsField) {
3221  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3222  return;
3223 
3224  // To record a shadowed field in a base
3225  std::map<CXXRecordDecl*, NamedDecl*> Bases;
3226  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3227  CXXBasePath &Path) {
3228  const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3229  // Record an ambiguous path directly
3230  if (Bases.find(Base) != Bases.end())
3231  return true;
3232  for (const auto Field : Base->lookup(FieldName)) {
3233  if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3234  Field->getAccess() != AS_private) {
3235  assert(Field->getAccess() != AS_none);
3236  assert(Bases.find(Base) == Bases.end());
3237  Bases[Base] = Field;
3238  return true;
3239  }
3240  }
3241  return false;
3242  };
3243 
3244  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3245  /*DetectVirtual=*/true);
3246  if (!RD->lookupInBases(FieldShadowed, Paths))
3247  return;
3248 
3249  for (const auto &P : Paths) {
3250  auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3251  auto It = Bases.find(Base);
3252  // Skip duplicated bases
3253  if (It == Bases.end())
3254  continue;
3255  auto BaseField = It->second;
3256  assert(BaseField->getAccess() != AS_private);
3257  if (AS_none !=
3258  CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3259  Diag(Loc, diag::warn_shadow_field)
3260  << FieldName << RD << Base << DeclIsField;
3261  Diag(BaseField->getLocation(), diag::note_shadow_field);
3262  Bases.erase(It);
3263  }
3264  }
3265 }
3266 
3267 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3268 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3269 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3270 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3271 /// present (but parsing it has been deferred).
3272 NamedDecl *
3274  MultiTemplateParamsArg TemplateParameterLists,
3275  Expr *BW, const VirtSpecifiers &VS,
3276  InClassInitStyle InitStyle) {
3277  const DeclSpec &DS = D.getDeclSpec();
3279  DeclarationName Name = NameInfo.getName();
3280  SourceLocation Loc = NameInfo.getLoc();
3281 
3282  // For anonymous bitfields, the location should point to the type.
3283  if (Loc.isInvalid())
3284  Loc = D.getBeginLoc();
3285 
3286  Expr *BitWidth = static_cast<Expr*>(BW);
3287 
3288  assert(isa<CXXRecordDecl>(CurContext));
3289  assert(!DS.isFriendSpecified());
3290 
3291  bool isFunc = D.isDeclarationOfFunction();
3292  const ParsedAttr *MSPropertyAttr =
3294 
3295  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3296  // The Microsoft extension __interface only permits public member functions
3297  // and prohibits constructors, destructors, operators, non-public member
3298  // functions, static methods and data members.
3299  unsigned InvalidDecl;
3300  bool ShowDeclName = true;
3301  if (!isFunc &&
3302  (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3303  InvalidDecl = 0;
3304  else if (!isFunc)
3305  InvalidDecl = 1;
3306  else if (AS != AS_public)
3307  InvalidDecl = 2;
3308  else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3309  InvalidDecl = 3;
3310  else switch (Name.getNameKind()) {
3312  InvalidDecl = 4;
3313  ShowDeclName = false;
3314  break;
3315 
3317  InvalidDecl = 5;
3318  ShowDeclName = false;
3319  break;
3320 
3323  InvalidDecl = 6;
3324  break;
3325 
3326  default:
3327  InvalidDecl = 0;
3328  break;
3329  }
3330 
3331  if (InvalidDecl) {
3332  if (ShowDeclName)
3333  Diag(Loc, diag::err_invalid_member_in_interface)
3334  << (InvalidDecl-1) << Name;
3335  else
3336  Diag(Loc, diag::err_invalid_member_in_interface)
3337  << (InvalidDecl-1) << "";
3338  return nullptr;
3339  }
3340  }
3341 
3342  // C++ 9.2p6: A member shall not be declared to have automatic storage
3343  // duration (auto, register) or with the extern storage-class-specifier.
3344  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3345  // data members and cannot be applied to names declared const or static,
3346  // and cannot be applied to reference members.
3347  switch (DS.getStorageClassSpec()) {
3349  case DeclSpec::SCS_typedef:
3350  case DeclSpec::SCS_static:
3351  break;
3352  case DeclSpec::SCS_mutable:
3353  if (isFunc) {
3354  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3355 
3356  // FIXME: It would be nicer if the keyword was ignored only for this
3357  // declarator. Otherwise we could get follow-up errors.
3359  }
3360  break;
3361  default:
3363  diag::err_storageclass_invalid_for_member);
3365  break;
3366  }
3367 
3368  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3370  !isFunc);
3371 
3372  if (DS.hasConstexprSpecifier() && isInstField) {
3374  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3375  SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3376  if (InitStyle == ICIS_NoInit) {
3377  B << 0 << 0;
3379  B << FixItHint::CreateRemoval(ConstexprLoc);
3380  else {
3381  B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3383  const char *PrevSpec;
3384  unsigned DiagID;
3385  bool Failed = D.getMutableDeclSpec().SetTypeQual(
3386  DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3387  (void)Failed;
3388  assert(!Failed && "Making a constexpr member const shouldn't fail");
3389  }
3390  } else {
3391  B << 1;
3392  const char *PrevSpec;
3393  unsigned DiagID;
3395  *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3397  assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3398  "This is the only DeclSpec that should fail to be applied");
3399  B << 1;
3400  } else {
3401  B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3402  isInstField = false;
3403  }
3404  }
3405  }
3406 
3407  NamedDecl *Member;
3408  if (isInstField) {
3409  CXXScopeSpec &SS = D.getCXXScopeSpec();
3410 
3411  // Data members must have identifiers for names.
3412  if (!Name.isIdentifier()) {
3413  Diag(Loc, diag::err_bad_variable_name)
3414  << Name;
3415  return nullptr;
3416  }
3417 
3418  IdentifierInfo *II = Name.getAsIdentifierInfo();
3419 
3420  // Member field could not be with "template" keyword.
3421  // So TemplateParameterLists should be empty in this case.
3422  if (TemplateParameterLists.size()) {
3423  TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3424  if (TemplateParams->size()) {
3425  // There is no such thing as a member field template.
3426  Diag(D.getIdentifierLoc(), diag::err_template_member)
3427  << II
3428  << SourceRange(TemplateParams->getTemplateLoc(),
3429  TemplateParams->getRAngleLoc());
3430  } else {
3431  // There is an extraneous 'template<>' for this member.
3432  Diag(TemplateParams->getTemplateLoc(),
3433  diag::err_template_member_noparams)
3434  << II
3435  << SourceRange(TemplateParams->getTemplateLoc(),
3436  TemplateParams->getRAngleLoc());
3437  }
3438  return nullptr;
3439  }
3440 
3442  Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3443  << II
3446  << D.getName().TemplateId->LAngleLoc;
3447  D.SetIdentifier(Name.getAsIdentifierInfo(), Loc);
3448  }
3449 
3450  if (SS.isSet() && !SS.isInvalid()) {
3451  // The user provided a superfluous scope specifier inside a class
3452  // definition:
3453  //
3454  // class X {
3455  // int X::member;
3456  // };
3457  if (DeclContext *DC = computeDeclContext(SS, false))
3459  D.getName().getKind() ==
3461  else
3462  Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3463  << Name << SS.getRange();
3464 
3465  SS.clear();
3466  }
3467 
3468  if (MSPropertyAttr) {
3469  Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3470  BitWidth, InitStyle, AS, *MSPropertyAttr);
3471  if (!Member)
3472  return nullptr;
3473  isInstField = false;
3474  } else {
3475  Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3476  BitWidth, InitStyle, AS);
3477  if (!Member)
3478  return nullptr;
3479  }
3480 
3481  CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3482  } else {
3483  Member = HandleDeclarator(S, D, TemplateParameterLists);
3484  if (!Member)
3485  return nullptr;
3486 
3487  // Non-instance-fields can't have a bitfield.
3488  if (BitWidth) {
3489  if (Member->isInvalidDecl()) {
3490  // don't emit another diagnostic.
3491  } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3492  // C++ 9.6p3: A bit-field shall not be a static member.
3493  // "static member 'A' cannot be a bit-field"
3494  Diag(Loc, diag::err_static_not_bitfield)
3495  << Name << BitWidth->getSourceRange();
3496  } else if (isa<TypedefDecl>(Member)) {
3497  // "typedef member 'x' cannot be a bit-field"
3498  Diag(Loc, diag::err_typedef_not_bitfield)
3499  << Name << BitWidth->getSourceRange();
3500  } else {
3501  // A function typedef ("typedef int f(); f a;").
3502  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3503  Diag(Loc, diag::err_not_integral_type_bitfield)
3504  << Name << cast<ValueDecl>(Member)->getType()
3505  << BitWidth->getSourceRange();
3506  }
3507 
3508  BitWidth = nullptr;
3509  Member->setInvalidDecl();
3510  }
3511 
3512  NamedDecl *NonTemplateMember = Member;
3513  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3514  NonTemplateMember = FunTmpl->getTemplatedDecl();
3515  else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3516  NonTemplateMember = VarTmpl->getTemplatedDecl();
3517 
3518  Member->setAccess(AS);
3519 
3520  // If we have declared a member function template or static data member
3521  // template, set the access of the templated declaration as well.
3522  if (NonTemplateMember != Member)
3523  NonTemplateMember->setAccess(AS);
3524 
3525  // C++ [temp.deduct.guide]p3:
3526  // A deduction guide [...] for a member class template [shall be
3527  // declared] with the same access [as the template].
3528  if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3529  auto *TD = DG->getDeducedTemplate();
3530  // Access specifiers are only meaningful if both the template and the
3531  // deduction guide are from the same scope.
3532  if (AS != TD->getAccess() &&
3533  TD->getDeclContext()->getRedeclContext()->Equals(
3534  DG->getDeclContext()->getRedeclContext())) {
3535  Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3536  Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3537  << TD->getAccess();
3538  const AccessSpecDecl *LastAccessSpec = nullptr;
3539  for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3540  if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3541  LastAccessSpec = AccessSpec;
3542  }
3543  assert(LastAccessSpec && "differing access with no access specifier");
3544  Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3545  << AS;
3546  }
3547  }
3548  }
3549 
3550  if (VS.isOverrideSpecified())
3551  Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3553  if (VS.isFinalSpecified())
3554  Member->addAttr(FinalAttr::Create(
3556  static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3557 
3558  if (VS.getLastLocation().isValid()) {
3559  // Update the end location of a method that has a virt-specifiers.
3560  if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3561  MD->setRangeEnd(VS.getLastLocation());
3562  }
3563 
3566 
3567  assert((Name || isInstField) && "No identifier for non-field ?");
3568 
3569  if (isInstField) {
3570  FieldDecl *FD = cast<FieldDecl>(Member);
3571  FieldCollector->Add(FD);
3572 
3573  if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3574  // Remember all explicit private FieldDecls that have a name, no side
3575  // effects and are not part of a dependent type declaration.
3576  if (!FD->isImplicit() && FD->getDeclName() &&
3577  FD->getAccess() == AS_private &&
3578  !FD->hasAttr<UnusedAttr>() &&
3579  !FD->getParent()->isDependentContext() &&
3581  UnusedPrivateFields.insert(FD);
3582  }
3583  }
3584 
3585  // Emit diagnostic if a private member of type decorated with device_global
3586  // attribute is accessed.
3587  if (getLangOpts().SYCLIsDevice) {
3588  if (auto Value = dyn_cast<ValueDecl>(Member)) {
3589  if (isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
3590  Value->getType()) &&
3591  Value->getAccess() != AS_public) {
3592  Diag(Loc, diag::err_sycl_device_global_not_publicly_accessible)
3593  << Value;
3594  }
3595  }
3596  }
3597 
3598  return Member;
3599 }
3600 
3601 namespace {
3602  class UninitializedFieldVisitor
3603  : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3604  Sema &S;
3605  // List of Decls to generate a warning on. Also remove Decls that become
3606  // initialized.
3607  llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3608  // List of base classes of the record. Classes are removed after their
3609  // initializers.
3610  llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3611  // Vector of decls to be removed from the Decl set prior to visiting the
3612  // nodes. These Decls may have been initialized in the prior initializer.
3613  llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3614  // If non-null, add a note to the warning pointing back to the constructor.
3615  const CXXConstructorDecl *Constructor;
3616  // Variables to hold state when processing an initializer list. When
3617  // InitList is true, special case initialization of FieldDecls matching
3618  // InitListFieldDecl.
3619  bool InitList;
3620  FieldDecl *InitListFieldDecl;
3621  llvm::SmallVector<unsigned, 4> InitFieldIndex;
3622 
3623  public:
3625  UninitializedFieldVisitor(Sema &S,
3626  llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3627  llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3628  : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3629  Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3630 
3631  // Returns true if the use of ME is not an uninitialized use.
3632  bool IsInitListMemberExprInitialized(MemberExpr *ME,
3633  bool CheckReferenceOnly) {
3635  bool ReferenceField = false;
3636  while (ME) {
3637  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3638  if (!FD)
3639  return false;
3640  Fields.push_back(FD);
3641  if (FD->getType()->isReferenceType())
3642  ReferenceField = true;
3643  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3644  }
3645 
3646  // Binding a reference to an uninitialized field is not an
3647  // uninitialized use.
3648  if (CheckReferenceOnly && !ReferenceField)
3649  return true;
3650 
3651  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3652  // Discard the first field since it is the field decl that is being
3653  // initialized.
3654  for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3655  UsedFieldIndex.push_back(FD->getFieldIndex());
3656 
3657  for (auto UsedIter = UsedFieldIndex.begin(),
3658  UsedEnd = UsedFieldIndex.end(),
3659  OrigIter = InitFieldIndex.begin(),
3660  OrigEnd = InitFieldIndex.end();
3661  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3662  if (*UsedIter < *OrigIter)
3663  return true;
3664  if (*UsedIter > *OrigIter)
3665  break;
3666  }
3667 
3668  return false;
3669  }
3670 
3671  void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3672  bool AddressOf) {
3673  if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3674  return;
3675 
3676  // FieldME is the inner-most MemberExpr that is not an anonymous struct
3677  // or union.
3678  MemberExpr *FieldME = ME;
3679 
3680  bool AllPODFields = FieldME->getType().isPODType(S.Context);
3681 
3682  Expr *Base = ME;
3683  while (MemberExpr *SubME =
3684  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3685 
3686  if (isa<VarDecl>(SubME->getMemberDecl()))
3687  return;
3688 
3689  if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3690  if (!FD->isAnonymousStructOrUnion())
3691  FieldME = SubME;
3692 
3693  if (!FieldME->getType().isPODType(S.Context))
3694  AllPODFields = false;
3695 
3696  Base = SubME->getBase();
3697  }
3698 
3699  if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3700  Visit(Base);
3701  return;
3702  }
3703 
3704  if (AddressOf && AllPODFields)
3705  return;
3706 
3707  ValueDecl* FoundVD = FieldME->getMemberDecl();
3708 
3709  if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3710  while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3711  BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3712  }
3713 
3714  if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3715  QualType T = BaseCast->getType();
3716  if (T->isPointerType() &&
3717  BaseClasses.count(T->getPointeeType())) {
3718  S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3719  << T->getPointeeType() << FoundVD;
3720  }
3721  }
3722  }
3723 
3724  if (!Decls.count(FoundVD))
3725  return;
3726 
3727  const bool IsReference = FoundVD->getType()->isReferenceType();
3728 
3729  if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3730  // Special checking for initializer lists.
3731  if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3732  return;
3733  }
3734  } else {
3735  // Prevent double warnings on use of unbounded references.
3736  if (CheckReferenceOnly && !IsReference)
3737  return;
3738  }
3739 
3740  unsigned diag = IsReference
3741  ? diag::warn_reference_field_is_uninit
3742  : diag::warn_field_is_uninit;
3743  S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3744  if (Constructor)
3745  S.Diag(Constructor->getLocation(),
3746  diag::note_uninit_in_this_constructor)
3747  << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3748 
3749  }
3750 
3751  void HandleValue(Expr *E, bool AddressOf) {
3752  E = E->IgnoreParens();
3753 
3754  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3755  HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3756  AddressOf /*AddressOf*/);
3757  return;
3758  }
3759 
3760  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3761  Visit(CO->getCond());
3762  HandleValue(CO->getTrueExpr(), AddressOf);
3763  HandleValue(CO->getFalseExpr(), AddressOf);
3764  return;
3765  }
3766 
3767  if (BinaryConditionalOperator *BCO =
3768  dyn_cast<BinaryConditionalOperator>(E)) {
3769  Visit(BCO->getCond());
3770  HandleValue(BCO->getFalseExpr(), AddressOf);
3771  return;
3772  }
3773 
3774  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3775  HandleValue(OVE->getSourceExpr(), AddressOf);
3776  return;
3777  }
3778 
3779  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3780  switch (BO->getOpcode()) {
3781  default:
3782  break;
3783  case(BO_PtrMemD):
3784  case(BO_PtrMemI):
3785  HandleValue(BO->getLHS(), AddressOf);
3786  Visit(BO->getRHS());
3787  return;
3788  case(BO_Comma):
3789  Visit(BO->getLHS());
3790  HandleValue(BO->getRHS(), AddressOf);
3791  return;
3792  }
3793  }
3794 
3795  Visit(E);
3796  }
3797 
3798  void CheckInitListExpr(InitListExpr *ILE) {
3799  InitFieldIndex.push_back(0);
3800  for (auto Child : ILE->children()) {
3801  if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3802  CheckInitListExpr(SubList);
3803  } else {
3804  Visit(Child);
3805  }
3806  ++InitFieldIndex.back();
3807  }
3808  InitFieldIndex.pop_back();
3809  }
3810 
3811  void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3812  FieldDecl *Field, const Type *BaseClass) {
3813  // Remove Decls that may have been initialized in the previous
3814  // initializer.
3815  for (ValueDecl* VD : DeclsToRemove)
3816  Decls.erase(VD);
3817  DeclsToRemove.clear();
3818 
3819  Constructor = FieldConstructor;
3820  InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3821 
3822  if (ILE && Field) {
3823  InitList = true;
3824  InitListFieldDecl = Field;
3825  InitFieldIndex.clear();
3826  CheckInitListExpr(ILE);
3827  } else {
3828  InitList = false;
3829  Visit(E);
3830  }
3831 
3832  if (Field)
3833  Decls.erase(Field);
3834  if (BaseClass)
3835  BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3836  }
3837 
3838  void VisitMemberExpr(MemberExpr *ME) {
3839  // All uses of unbounded reference fields will warn.
3840  HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3841  }
3842 
3843  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3844  if (E->getCastKind() == CK_LValueToRValue) {
3845  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3846  return;
3847  }
3848 
3849  Inherited::VisitImplicitCastExpr(E);
3850  }
3851 
3852  void VisitCXXConstructExpr(CXXConstructExpr *E) {
3853  if (E->getConstructor()->isCopyConstructor()) {
3854  Expr *ArgExpr = E->getArg(0);
3855  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3856  if (ILE->getNumInits() == 1)
3857  ArgExpr = ILE->getInit(0);
3858  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3859  if (ICE->getCastKind() == CK_NoOp)
3860  ArgExpr = ICE->getSubExpr();
3861  HandleValue(ArgExpr, false /*AddressOf*/);
3862  return;
3863  }
3864  Inherited::VisitCXXConstructExpr(E);
3865  }
3866 
3867  void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3868  Expr *Callee = E->getCallee();
3869  if (isa<MemberExpr>(Callee)) {
3870  HandleValue(Callee, false /*AddressOf*/);
3871  for (auto Arg : E->arguments())
3872  Visit(Arg);
3873  return;
3874  }
3875 
3876  Inherited::VisitCXXMemberCallExpr(E);
3877  }
3878 
3879  void VisitCallExpr(CallExpr *E) {
3880  // Treat std::move as a use.
3881  if (E->isCallToStdMove()) {
3882  HandleValue(E->getArg(0), /*AddressOf=*/false);
3883  return;
3884  }
3885 
3886  Inherited::VisitCallExpr(E);
3887  }
3888 
3889  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3890  Expr *Callee = E->getCallee();
3891 
3892  if (isa<UnresolvedLookupExpr>(Callee))
3893  return Inherited::VisitCXXOperatorCallExpr(E);
3894 
3895  Visit(Callee);
3896  for (auto Arg : E->arguments())
3897  HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3898  }
3899 
3900  void VisitBinaryOperator(BinaryOperator *E) {
3901  // If a field assignment is detected, remove the field from the
3902  // uninitiailized field set.
3903  if (E->getOpcode() == BO_Assign)
3904  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3905  if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3906  if (!FD->getType()->isReferenceType())
3907  DeclsToRemove.push_back(FD);
3908 
3909  if (E->isCompoundAssignmentOp()) {
3910  HandleValue(E->getLHS(), false /*AddressOf*/);
3911  Visit(E->getRHS());
3912  return;
3913  }
3914 
3915  Inherited::VisitBinaryOperator(E);
3916  }
3917 
3918  void VisitUnaryOperator(UnaryOperator *E) {
3919  if (E->isIncrementDecrementOp()) {
3920  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3921  return;
3922  }
3923  if (E->getOpcode() == UO_AddrOf) {
3924  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3925  HandleValue(ME->getBase(), true /*AddressOf*/);
3926  return;
3927  }
3928  }
3929 
3930  Inherited::VisitUnaryOperator(E);
3931  }
3932  };
3933 
3934  // Diagnose value-uses of fields to initialize themselves, e.g.
3935  // foo(foo)
3936  // where foo is not also a parameter to the constructor.
3937  // Also diagnose across field uninitialized use such as
3938  // x(y), y(x)
3939  // TODO: implement -Wuninitialized and fold this into that framework.
3940  static void DiagnoseUninitializedFields(
3941  Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3942 
3943  if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3944  Constructor->getLocation())) {
3945  return;
3946  }
3947 
3948  if (Constructor->isInvalidDecl())
3949  return;
3950 
3951  const CXXRecordDecl *RD = Constructor->getParent();
3952 
3953  if (RD->isDependentContext())
3954  return;
3955 
3956  // Holds fields that are uninitialized.
3957  llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3958 
3959  // At the beginning, all fields are uninitialized.
3960  for (auto *I : RD->decls()) {
3961  if (auto *FD = dyn_cast<FieldDecl>(I)) {
3962  UninitializedFields.insert(FD);
3963  } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3964  UninitializedFields.insert(IFD->getAnonField());
3965  }
3966  }
3967 
3968  llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3969  for (auto I : RD->bases())
3970  UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3971 
3972  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3973  return;
3974 
3975  UninitializedFieldVisitor UninitializedChecker(SemaRef,
3976  UninitializedFields,
3977  UninitializedBaseClasses);
3978 
3979  for (const auto *FieldInit : Constructor->inits()) {
3980  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3981  break;
3982 
3983  Expr *InitExpr = FieldInit->getInit();
3984  if (!InitExpr)
3985  continue;
3986 
3987  if (CXXDefaultInitExpr *Default =
3988  dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3989  InitExpr = Default->getExpr();
3990  if (!InitExpr)
3991  continue;
3992  // In class initializers will point to the constructor.
3993  UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3994  FieldInit->getAnyMember(),
3995  FieldInit->getBaseClass());
3996  } else {
3997  UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3998  FieldInit->getAnyMember(),
3999  FieldInit->getBaseClass());
4000  }
4001  }
4002  }
4003 } // namespace
4004 
4005 /// Enter a new C++ default initializer scope. After calling this, the
4006 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4007 /// parsing or instantiating the initializer failed.
4009  // Create a synthetic function scope to represent the call to the constructor
4010  // that notionally surrounds a use of this initializer.
4012 }
4013 
4015  if (!D.isFunctionDeclarator())
4016  return;
4017  auto &FTI = D.getFunctionTypeInfo();
4018  if (!FTI.Params)
4019  return;
4020  for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4021  FTI.NumParams)) {
4022  auto *ParamDecl = cast<NamedDecl>(Param.Param);
4023  if (ParamDecl->getDeclName())
4024  PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4025  }
4026 }
4027 
4029  return ActOnRequiresClause(ConstraintExpr);
4030 }
4031 
4033  if (ConstraintExpr.isInvalid())
4034  return ExprError();
4035 
4036  ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4037  if (ConstraintExpr.isInvalid())
4038  return ExprError();
4039 
4040  if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4042  return ExprError();
4043 
4044  return ConstraintExpr;
4045 }
4046 
4047 /// This is invoked after parsing an in-class initializer for a
4048 /// non-static C++ class member, and after instantiating an in-class initializer
4049 /// in a class template. Such actions are deferred until the class is complete.
4051  SourceLocation InitLoc,
4052  Expr *InitExpr) {
4053  // Pop the notional constructor scope we created earlier.
4054  PopFunctionScopeInfo(nullptr, D);
4055 
4056  FieldDecl *FD = dyn_cast<FieldDecl>(D);
4057  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4058  "must set init style when field is created");
4059 
4060  if (!InitExpr) {
4061  D->setInvalidDecl();
4062  if (FD)
4064  return;
4065  }
4066 
4068  FD->setInvalidDecl();
4070  return;
4071  }
4072 
4073  ExprResult Init = InitExpr;
4074  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4075  InitializedEntity Entity =
4080  InitExpr->getBeginLoc(),
4081  InitExpr->getEndLoc())
4082  : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4083  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4084  Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4085  if (Init.isInvalid()) {
4086  FD->setInvalidDecl();
4087  return;
4088  }
4089  }
4090 
4091  // C++11 [class.base.init]p7:
4092  // The initialization of each base and member constitutes a
4093  // full-expression.
4094  Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4095  if (Init.isInvalid()) {
4096  FD->setInvalidDecl();
4097  return;
4098  }
4099 
4100  InitExpr = Init.get();
4101 
4102  FD->setInClassInitializer(InitExpr);
4103 }
4104 
4105 /// Find the direct and/or virtual base specifiers that
4106 /// correspond to the given base type, for use in base initialization
4107 /// within a constructor.
4108 static bool FindBaseInitializer(Sema &SemaRef,
4109  CXXRecordDecl *ClassDecl,
4110  QualType BaseType,
4111  const CXXBaseSpecifier *&DirectBaseSpec,
4112  const CXXBaseSpecifier *&VirtualBaseSpec) {
4113  // First, check for a direct base class.
4114  DirectBaseSpec = nullptr;
4115  for (const auto &Base : ClassDecl->bases()) {
4116  if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4117  // We found a direct base of this type. That's what we're
4118  // initializing.
4119  DirectBaseSpec = &Base;
4120  break;
4121  }
4122  }
4123 
4124  // Check for a virtual base class.
4125  // FIXME: We might be able to short-circuit this if we know in advance that
4126  // there are no virtual bases.
4127  VirtualBaseSpec = nullptr;
4128  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4129  // We haven't found a base yet; search the class hierarchy for a
4130  // virtual base class.
4131  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4132  /*DetectVirtual=*/false);
4133  if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4134  SemaRef.Context.getTypeDeclType(ClassDecl),
4135  BaseType, Paths)) {
4136  for (CXXBasePaths::paths_iterator Path = Paths.begin();
4137  Path != Paths.end(); ++Path) {
4138  if (Path->back().Base->isVirtual()) {
4139  VirtualBaseSpec = Path->back().Base;
4140  break;
4141  }
4142  }
4143  }
4144  }
4145 
4146  return DirectBaseSpec || VirtualBaseSpec;
4147 }
4148 
4149 /// Handle a C++ member initializer using braced-init-list syntax.
4152  Scope *S,
4153  CXXScopeSpec &SS,
4154  IdentifierInfo *MemberOrBase,
4155  ParsedType TemplateTypeTy,
4156  const DeclSpec &DS,
4157  SourceLocation IdLoc,
4158  Expr *InitList,
4159  SourceLocation EllipsisLoc) {
4160  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4161  DS, IdLoc, InitList,
4162  EllipsisLoc);
4163 }
4164 
4165 /// Handle a C++ member initializer using parentheses syntax.
4168  Scope *S,
4169  CXXScopeSpec &SS,
4170  IdentifierInfo *MemberOrBase,
4171  ParsedType TemplateTypeTy,
4172  const DeclSpec &DS,
4173  SourceLocation IdLoc,
4174  SourceLocation LParenLoc,
4175  ArrayRef<Expr *> Args,
4176  SourceLocation RParenLoc,
4177  SourceLocation EllipsisLoc) {
4178  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4179  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4180  DS, IdLoc, List, EllipsisLoc);
4181 }
4182 
4183 namespace {
4184 
4185 // Callback to only accept typo corrections that can be a valid C++ member
4186 // initializer: either a non-static field member or a base class.
4187 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4188 public:
4189  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4190  : ClassDecl(ClassDecl) {}
4191 
4192  bool ValidateCandidate(const TypoCorrection &candidate) override {
4193  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4194  if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4195  return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4196  return isa<TypeDecl>(ND);
4197  }
4198  return false;
4199  }
4200 
4201  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4202  return std::make_unique<MemInitializerValidatorCCC>(*this);
4203  }
4204 
4205 private:
4206  CXXRecordDecl *ClassDecl;
4207 };
4208 
4209 }
4210 
4211 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4212  CXXScopeSpec &SS,
4213  ParsedType TemplateTypeTy,
4214  IdentifierInfo *MemberOrBase) {
4215  if (SS.getScopeRep() || TemplateTypeTy)
4216  return nullptr;
4217  for (auto *D : ClassDecl->lookup(MemberOrBase))
4218  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4219  return cast<ValueDecl>(D);
4220  return nullptr;
4221 }
4222 
4223 /// Handle a C++ member initializer.
4226  Scope *S,
4227  CXXScopeSpec &SS,
4228  IdentifierInfo *MemberOrBase,
4229  ParsedType TemplateTypeTy,
4230  const DeclSpec &DS,
4231  SourceLocation IdLoc,
4232  Expr *Init,
4233  SourceLocation EllipsisLoc) {
4234  ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4235  /*RecoverUncorrectedTypos=*/true);
4236  if (!Res.isUsable())
4237  return true;
4238  Init = Res.get();
4239 
4240  if (!ConstructorD)
4241  return true;
4242 
4243  AdjustDeclIfTemplate(ConstructorD);
4244 
4245  CXXConstructorDecl *Constructor
4246  = dyn_cast<CXXConstructorDecl>(ConstructorD);
4247  if (!Constructor) {
4248  // The user wrote a constructor initializer on a function that is
4249  // not a C++ constructor. Ignore the error for now, because we may
4250  // have more member initializers coming; we'll diagnose it just
4251  // once in ActOnMemInitializers.
4252  return true;
4253  }
4254 
4255  CXXRecordDecl *ClassDecl = Constructor->getParent();
4256 
4257  // C++ [class.base.init]p2:
4258  // Names in a mem-initializer-id are looked up in the scope of the
4259  // constructor's class and, if not found in that scope, are looked
4260  // up in the scope containing the constructor's definition.
4261  // [Note: if the constructor's class contains a member with the
4262  // same name as a direct or virtual base class of the class, a
4263  // mem-initializer-id naming the member or base class and composed
4264  // of a single identifier refers to the class member. A
4265  // mem-initializer-id for the hidden base class may be specified
4266  // using a qualified name. ]
4267 
4268  // Look for a member, first.
4269  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4270  ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4271  if (EllipsisLoc.isValid())
4272  Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4273  << MemberOrBase
4274  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4275 
4276  return BuildMemberInitializer(Member, Init, IdLoc);
4277  }
4278  // It didn't name a member, so see if it names a class.
4279  QualType BaseType;
4280  TypeSourceInfo *TInfo = nullptr;
4281 
4282  if (TemplateTypeTy) {
4283  BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4284  if (BaseType.isNull())
4285  return true;
4286  } else if (DS.getTypeSpecType() == TST_decltype) {
4287  BaseType = BuildDecltypeType(DS.getRepAsExpr());
4288  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4289  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4290  return true;
4291  } else {
4292  LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4293  LookupParsedName(R, S, &SS);
4294 
4295  TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4296  if (!TyD) {
4297  if (R.isAmbiguous()) return true;
4298 
4299  // We don't want access-control diagnostics here.
4300  R.suppressDiagnostics();
4301 
4302  if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4303  bool NotUnknownSpecialization = false;
4304  DeclContext *DC = computeDeclContext(SS, false);
4305  if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4306  NotUnknownSpecialization = !Record->hasAnyDependentBases();
4307 
4308  if (!NotUnknownSpecialization) {
4309  // When the scope specifier can refer to a member of an unknown
4310  // specialization, we take it as a type name.
4313  *MemberOrBase, IdLoc);
4314  if (BaseType.isNull())
4315  return true;
4316 
4317  TInfo = Context.CreateTypeSourceInfo(BaseType);
4320  if (!TL.isNull()) {
4321  TL.setNameLoc(IdLoc);
4324  }
4325 
4326  R.clear();
4327  R.setLookupName(MemberOrBase);
4328  }
4329  }
4330 
4331  // If no results were found, try to correct typos.
4332  TypoCorrection Corr;
4333  MemInitializerValidatorCCC CCC(ClassDecl);
4334  if (R.empty() && BaseType.isNull() &&
4335  (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4336  CCC, CTK_ErrorRecovery, ClassDecl))) {
4337  if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4338  // We have found a non-static data member with a similar
4339  // name to what was typed; complain and initialize that
4340  // member.
4341  diagnoseTypo(Corr,
4342  PDiag(diag::err_mem_init_not_member_or_class_suggest)
4343  << MemberOrBase << true);
4344  return BuildMemberInitializer(Member, Init, IdLoc);
4345  } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4346  const CXXBaseSpecifier *DirectBaseSpec;
4347  const CXXBaseSpecifier *VirtualBaseSpec;
4348  if (FindBaseInitializer(*this, ClassDecl,
4350  DirectBaseSpec, VirtualBaseSpec)) {
4351  // We have found a direct or virtual base class with a
4352  // similar name to what was typed; complain and initialize
4353  // that base class.
4354  diagnoseTypo(Corr,
4355  PDiag(diag::err_mem_init_not_member_or_class_suggest)
4356  << MemberOrBase << false,
4357  PDiag() /*Suppress note, we provide our own.*/);
4358 
4359  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4360  : VirtualBaseSpec;
4361  Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4362  << BaseSpec->getType() << BaseSpec->getSourceRange();
4363 
4364  TyD = Type;
4365  }
4366  }
4367  }
4368 
4369  if (!TyD && BaseType.isNull()) {
4370  Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4371  << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4372  return true;
4373  }
4374  }
4375 
4376  if (BaseType.isNull()) {
4377  BaseType = Context.getTypeDeclType(TyD);
4378  MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4379  if (SS.isSet()) {
4380  BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4381  BaseType);
4382  TInfo = Context.CreateTypeSourceInfo(BaseType);
4384  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4387  }
4388  }
4389  }
4390 
4391  if (!TInfo)
4392  TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4393 
4394  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4395 }
4396 
4399  SourceLocation IdLoc) {
4400  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4401  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4402  assert((DirectMember || IndirectMember) &&
4403  "Member must be a FieldDecl or IndirectFieldDecl");
4404 
4406  return true;
4407 
4408  if (Member->isInvalidDecl())
4409  return true;
4410 
4411  MultiExprArg Args;
4412  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4413  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4414  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4415  Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4416  } else {
4417  // Template instantiation doesn't reconstruct ParenListExprs for us.
4418  Args = Init;
4419  }
4420 
4421  SourceRange InitRange = Init->getSourceRange();
4422 
4423  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4424  // Can't check initialization for a member of dependent type or when
4425  // any of the arguments are type-dependent expressions.
4427  } else {
4428  bool InitList = false;
4429  if (isa<InitListExpr>(Init)) {
4430  InitList = true;
4431  Args = Init;
4432  }
4433 
4434  // Initialize the member.
4435  InitializedEntity MemberEntity =
4436  DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4437  : InitializedEntity::InitializeMember(IndirectMember,
4438  nullptr);
4441  IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4442  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4443  InitRange.getEnd());
4444 
4445  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4446  ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4447  nullptr);
4448  if (!MemberInit.isInvalid()) {
4449  // C++11 [class.base.init]p7:
4450  // The initialization of each base and member constitutes a
4451  // full-expression.
4452  MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4453  /*DiscardedValue*/ false);
4454  }
4455 
4456  if (MemberInit.isInvalid()) {
4457  // Args were sensible expressions but we couldn't initialize the member
4458  // from them. Preserve them in a RecoveryExpr instead.
4459  Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4460  Member->getType())
4461  .get();
4462  if (!Init)
4463  return true;
4464  } else {
4465  Init = MemberInit.get();
4466  }
4467  }
4468 
4469  if (DirectMember) {
4470  return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4471  InitRange.getBegin(), Init,
4472  InitRange.getEnd());
4473  } else {
4474  return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4475  InitRange.getBegin(), Init,
4476  InitRange.getEnd());
4477  }
4478 }
4479 
4482  CXXRecordDecl *ClassDecl) {
4483  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4484  if (!LangOpts.CPlusPlus11)
4485  return Diag(NameLoc, diag::err_delegating_ctor)
4486  << TInfo->getTypeLoc().getLocalSourceRange();
4487  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4488 
4489  bool InitList = true;
4490  MultiExprArg Args = Init;
4491  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4492  InitList = false;
4493  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4494  }
4495 
4496  SourceRange InitRange = Init->getSourceRange();
4497  // Initialize the object.
4499  QualType(ClassDecl->getTypeForDecl(), 0));
4502  NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4503  : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4504  InitRange.getEnd());
4505  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4506  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4507  Args, nullptr);
4508  if (!DelegationInit.isInvalid()) {
4509  assert((DelegationInit.get()->containsErrors() ||
4510  cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4511  "Delegating constructor with no target?");
4512 
4513  // C++11 [class.base.init]p7:
4514  // The initialization of each base and member constitutes a
4515  // full-expression.
4516  DelegationInit = ActOnFinishFullExpr(
4517  DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4518  }
4519 
4520  if (DelegationInit.isInvalid()) {
4521  DelegationInit =
4522  CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4523  QualType(ClassDecl->getTypeForDecl(), 0));
4524  if (DelegationInit.isInvalid())
4525  return true;
4526  } else {
4527  // If we are in a dependent context, template instantiation will
4528  // perform this type-checking again. Just save the arguments that we
4529  // received in a ParenListExpr.
4530  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4531  // of the information that we have about the base
4532  // initializer. However, deconstructing the ASTs is a dicey process,
4533  // and this approach is far more likely to get the corner cases right.
4535  DelegationInit = Init;
4536  }
4537 
4538  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4539  DelegationInit.getAs<Expr>(),
4540  InitRange.getEnd());
4541 }
4542 
4545  Expr *Init, CXXRecordDecl *ClassDecl,
4546  SourceLocation EllipsisLoc) {
4547  SourceLocation BaseLoc
4548  = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4549 
4550  if (!BaseType->isDependentType() && !BaseType->isRecordType())
4551  return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4552  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4553 
4554  // C++ [class.base.init]p2:
4555  // [...] Unless the mem-initializer-id names a nonstatic data
4556  // member of the constructor's class or a direct or virtual base
4557  // of that class, the mem-initializer is ill-formed. A
4558  // mem-initializer-list can initialize a base class using any
4559  // name that denotes that base class type.
4560 
4561  // We can store the initializers in "as-written" form and delay analysis until
4562  // instantiation if the constructor is dependent. But not for dependent
4563  // (broken) code in a non-template! SetCtorInitializers does not expect this.
4564  bool Dependent = CurContext->isDependentContext() &&
4565  (BaseType->isDependentType() || Init->isTypeDependent());
4566 
4567  SourceRange InitRange = Init->getSourceRange();
4568  if (EllipsisLoc.isValid()) {
4569  // This is a pack expansion.
4570  if (!BaseType->containsUnexpandedParameterPack()) {
4571  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4572  << SourceRange(BaseLoc, InitRange.getEnd());
4573 
4574  EllipsisLoc = SourceLocation();
4575  }
4576  } else {
4577  // Check for any unexpanded parameter packs.
4578  if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4579  return true;
4580 
4582  return true;
4583  }
4584 
4585  // Check for direct and virtual base classes.
4586  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4587  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4588  if (!Dependent) {
4590  BaseType))
4591  return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4592 
4593  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4594  VirtualBaseSpec);
4595 
4596  // C++ [base.class.init]p2:
4597  // Unless the mem-initializer-id names a nonstatic data member of the
4598  // constructor's class or a direct or virtual base of that class, the
4599  // mem-initializer is ill-formed.
4600  if (!DirectBaseSpec && !VirtualBaseSpec) {
4601  // If the class has any dependent bases, then it's possible that
4602  // one of those types will resolve to the same type as
4603  // BaseType. Therefore, just treat this as a dependent base
4604  // class initialization. FIXME: Should we try to check the
4605  // initialization anyway? It seems odd.
4606  if (ClassDecl->hasAnyDependentBases())
4607  Dependent = true;
4608  else
4609  return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4610  << BaseType << Context.getTypeDeclType(ClassDecl)
4611  << BaseTInfo->getTypeLoc().getLocalSourceRange();
4612  }
4613  }
4614 
4615  if (Dependent) {
4617 
4618  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4619  /*IsVirtual=*/false,
4620  InitRange.getBegin(), Init,
4621  InitRange.getEnd(), EllipsisLoc);
4622  }
4623 
4624  // C++ [base.class.init]p2:
4625  // If a mem-initializer-id is ambiguous because it designates both
4626  // a direct non-virtual base class and an inherited virtual base
4627  // class, the mem-initializer is ill-formed.
4628  if (DirectBaseSpec && VirtualBaseSpec)
4629  return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4630  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4631 
4632  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4633  if (!BaseSpec)
4634  BaseSpec = VirtualBaseSpec;
4635 
4636  // Initialize the base.
4637  bool InitList = true;
4638  MultiExprArg Args = Init;
4639  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4640  InitList = false;
4641  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4642  }
4643 
4644  InitializedEntity BaseEntity =
4645  InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4647  InitList ? InitializationKind::CreateDirectList(BaseLoc)
4648  : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4649  InitRange.getEnd());
4650  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4651  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4652  if (!BaseInit.isInvalid()) {
4653  // C++11 [class.base.init]p7:
4654  // The initialization of each base and member constitutes a
4655  // full-expression.
4656  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4657  /*DiscardedValue*/ false);
4658  }
4659 
4660  if (BaseInit.isInvalid()) {
4661  BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4662  Args, BaseType);
4663  if (BaseInit.isInvalid())
4664  return true;
4665  } else {
4666  // If we are in a dependent context, template instantiation will
4667  // perform this type-checking again. Just save the arguments that we
4668  // received in a ParenListExpr.
4669  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4670  // of the information that we have about the base
4671  // initializer. However, deconstructing the ASTs is a dicey process,
4672  // and this approach is far more likely to get the corner cases right.
4674  BaseInit = Init;
4675  }
4676 
4677  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4678  BaseSpec->isVirtual(),
4679  InitRange.getBegin(),
4680  BaseInit.getAs<Expr>(),
4681  InitRange.getEnd(), EllipsisLoc);
4682 }
4683 
4684 // Create a static_cast<T&&>(expr).
4685 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4686  if (T.isNull()) T = E->getType();
4687  QualType TargetType = SemaRef.BuildReferenceType(
4688  T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4689  SourceLocation ExprLoc = E->getBeginLoc();
4690  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4691  TargetType, ExprLoc);
4692 
4693  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4694  SourceRange(ExprLoc, ExprLoc),
4695  E->getSourceRange()).get();
4696 }
4697 
4698 /// ImplicitInitializerKind - How an implicit base or member initializer should
4699 /// initialize its base or member.
4705 };
4706 
4707 static bool
4709  ImplicitInitializerKind ImplicitInitKind,
4710  CXXBaseSpecifier *BaseSpec,
4711  bool IsInheritedVirtualBase,
4712  CXXCtorInitializer *&CXXBaseInit) {
4713  InitializedEntity InitEntity
4714  = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4715  IsInheritedVirtualBase);
4716 
4717  ExprResult BaseInit;
4718 
4719  switch (ImplicitInitKind) {
4720  case IIK_Inherit:
4721  case IIK_Default: {
4722  InitializationKind InitKind
4723  = InitializationKind::CreateDefault(Constructor->getLocation());
4724  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4725  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4726  break;
4727  }
4728 
4729  case IIK_Move:
4730  case IIK_Copy: {
4731  bool Moving = ImplicitInitKind == IIK_Move;
4732  ParmVarDecl *Param = Constructor->getParamDecl(0);
4733  QualType ParamType = Param->getType().getNonReferenceType();
4734 
4735  Expr *CopyCtorArg =
4737  SourceLocation(), Param, false,
4738  Constructor->getLocation(), ParamType,
4739  VK_LValue, nullptr);
4740 
4741  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4742 
4743  // Cast to the base class to avoid ambiguities.
4744  QualType ArgTy =
4745  SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4746  ParamType.getQualifiers());
4747 
4748  if (Moving) {
4749  CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4750  }
4751 
4752  CXXCastPath BasePath;
4753  BasePath.push_back(BaseSpec);
4754  CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4755  CK_UncheckedDerivedToBase,
4756  Moving ? VK_XValue : VK_LValue,
4757  &BasePath).get();
4758 
4759  InitializationKind InitKind
4760  = InitializationKind::CreateDirect(Constructor->getLocation(),
4762  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4763  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4764  break;
4765  }
4766  }
4767 
4768  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4769  if (BaseInit.isInvalid())
4770  return true;
4771 
4772  CXXBaseInit =
4773  new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4774  SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4775  SourceLocation()),
4776  BaseSpec->isVirtual(),
4777  SourceLocation(),
4778  BaseInit.getAs<Expr>(),
4779  SourceLocation(),
4780  SourceLocation());
4781 
4782  return false;
4783 }
4784 
4785 static bool RefersToRValueRef(Expr *MemRef) {
4786  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4787  return Referenced->getType()->isRValueReferenceType();
4788 }
4789 
4790 static bool
4792  ImplicitInitializerKind ImplicitInitKind,
4793  FieldDecl *Field, IndirectFieldDecl *Indirect,
4794  CXXCtorInitializer *&CXXMemberInit) {
4795  if (Field->isInvalidDecl())
4796  return true;
4797 
4798  SourceLocation Loc = Constructor->getLocation();
4799 
4800  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4801  bool Moving = ImplicitInitKind == IIK_Move;
4802  ParmVarDecl *Param = Constructor->getParamDecl(0);
4803  QualType ParamType = Param->getType().getNonReferenceType();
4804 
4805  // Suppress copying zero-width bitfields.
4806  if (Field->isZeroLengthBitField(SemaRef.Context))
4807  return false;
4808 
4809  Expr *MemberExprBase =
4811  SourceLocation(), Param, false,
4812  Loc, ParamType, VK_LValue, nullptr);
4813 
4814  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4815 
4816  if (Moving) {
4817  MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4818  }
4819 
4820  // Build a reference to this field within the parameter.
4821  CXXScopeSpec SS;
4822  LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4824  MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4825  : cast<ValueDecl>(Field), AS_public);
4826  MemberLookup.resolveKind();
4827  ExprResult CtorArg
4828  = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4829  ParamType, Loc,
4830  /*IsArrow=*/false,
4831  SS,
4832  /*TemplateKWLoc=*/SourceLocation(),
4833  /*FirstQualifierInScope=*/nullptr,
4834  MemberLookup,
4835  /*TemplateArgs=*/nullptr,
4836  /*S*/nullptr);
4837  if (CtorArg.isInvalid())
4838  return true;
4839 
4840  // C++11 [class.copy]p15:
4841  // - if a member m has rvalue reference type T&&, it is direct-initialized
4842  // with static_cast<T&&>(x.m);
4843  if (RefersToRValueRef(CtorArg.get())) {
4844  CtorArg = CastForMoving(SemaRef, CtorArg.get());
4845  }
4846 
4847  InitializedEntity Entity =
4848  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4849  /*Implicit*/ true)
4850  : InitializedEntity::InitializeMember(Field, nullptr,
4851  /*Implicit*/ true);
4852 
4853  // Direct-initialize to use the copy constructor.
4854  InitializationKind InitKind =
4856 
4857  Expr *CtorArgE = CtorArg.getAs<Expr>();
4858  InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4859  ExprResult MemberInit =
4860  InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4861  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4862  if (MemberInit.isInvalid())
4863  return true;
4864 
4865  if (Indirect)
4866  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4867  SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4868  else
4869  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4870  SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4871  return false;
4872  }
4873 
4874  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4875  "Unhandled implicit init kind!");
4876 
4877  QualType FieldBaseElementType =
4878  SemaRef.Context.getBaseElementType(Field->getType());
4879 
4880  if (FieldBaseElementType->isRecordType()) {
4881  InitializedEntity InitEntity =
4882  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4883  /*Implicit*/ true)
4884  : InitializedEntity::InitializeMember(Field, nullptr,
4885  /*Implicit*/ true);
4886  InitializationKind InitKind =
4888 
4889  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4890  ExprResult MemberInit =
4891  InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4892 
4893  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4894  if (MemberInit.isInvalid())
4895  return true;
4896 
4897  if (Indirect)
4898  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4899  Indirect, Loc,
4900  Loc,
4901  MemberInit.get(),
4902  Loc);
4903  else
4904  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4905  Field, Loc, Loc,
4906  MemberInit.get(),
4907  Loc);
4908  return false;
4909  }
4910 
4911  if (!Field->getParent()->isUnion()) {
4912  if (FieldBaseElementType->isReferenceType()) {
4913  SemaRef.Diag(Constructor->getLocation(),
4914  diag::err_uninitialized_member_in_ctor)
4915  << (int)Constructor->isImplicit()
4916  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4917  << 0 << Field->getDeclName();
4918  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4919  return true;
4920  }
4921 
4922  if (FieldBaseElementType.isConstQualified()) {
4923  SemaRef.Diag(Constructor->getLocation(),
4924  diag::err_uninitialized_member_in_ctor)
4925  << (int)Constructor->isImplicit()
4926  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4927  << 1 << Field->getDeclName();
4928  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4929  return true;
4930  }
4931  }
4932 
4933  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4934  // ARC and Weak:
4935  // Default-initialize Objective-C pointers to NULL.
4936  CXXMemberInit
4937  = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4938  Loc, Loc,
4939  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4940  Loc);
4941  return false;
4942  }
4943 
4944  // Nothing to initialize.
4945  CXXMemberInit = nullptr;
4946  return false;
4947 }
4948 
4949 namespace {
4950 struct BaseAndFieldInfo {
4951  Sema &S;
4952  CXXConstructorDecl *Ctor;
4953  bool AnyErrorsInInits;
4955  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4957  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4958 
4959  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4960  : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4961  bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4962  if (Ctor->getInheritedConstructor())
4963  IIK = IIK_Inherit;
4964  else if (Generated && Ctor->isCopyConstructor())
4965  IIK = IIK_Copy;
4966  else if (Generated && Ctor->isMoveConstructor())
4967  IIK = IIK_Move;
4968  else
4969  IIK = IIK_Default;
4970  }
4971 
4972  bool isImplicitCopyOrMove() const {
4973  switch (IIK) {
4974  case IIK_Copy:
4975  case IIK_Move:
4976  return true;
4977 
4978  case IIK_Default:
4979  case IIK_Inherit:
4980  return false;
4981  }
4982 
4983  llvm_unreachable("Invalid ImplicitInitializerKind!");
4984  }
4985 
4986  bool addFieldInitializer(CXXCtorInitializer *Init) {
4987  AllToInit.push_back(Init);
4988 
4989  // Check whether this initializer makes the field "used".
4990  if (Init->getInit()->HasSideEffects(S.Context))
4991  S.UnusedPrivateFields.remove(Init->getAnyMember());
4992 
4993  return false;
4994  }
4995 
4996  bool isInactiveUnionMember(FieldDecl *Field) {
4997  RecordDecl *Record = Field->getParent();
4998  if (!Record->isUnion())
4999  return false;
5000 
5001  if (FieldDecl *Active =
5002  ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5003  return Active != Field->getCanonicalDecl();
5004 
5005  // In an implicit copy or move constructor, ignore any in-class initializer.
5006  if (isImplicitCopyOrMove())
5007  return true;
5008 
5009  // If there's no explicit initialization, the field is active only if it
5010  // has an in-class initializer...
5011  if (Field->hasInClassInitializer())
5012  return false;
5013  // ... or it's an anonymous struct or union whose class has an in-class
5014  // initializer.
5015  if (!Field->isAnonymousStructOrUnion())
5016  return true;
5017  CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5018  return !FieldRD->hasInClassInitializer();
5019  }
5020 
5021  /// Determine whether the given field is, or is within, a union member
5022  /// that is inactive (because there was an initializer given for a different
5023  /// member of the union, or because the union was not initialized at all).
5024  bool isWithinInactiveUnionMember(FieldDecl *Field,
5025  IndirectFieldDecl *Indirect) {
5026  if (!Indirect)
5027  return isInactiveUnionMember(Field);
5028 
5029  for (auto *C : Indirect->chain()) {
5030  FieldDecl *Field = dyn_cast<FieldDecl>(C);
5031  if (Field && isInactiveUnionMember(Field))
5032  return true;
5033  }
5034  return false;
5035  }
5036 };
5037 }
5038 
5039 /// Determine whether the given type is an incomplete or zero-lenfgth
5040 /// array type.
5042  if (T->isIncompleteArrayType())
5043  return true;
5044 
5045  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5046  if (!ArrayT->getSize())
5047  return true;
5048 
5049  T = ArrayT->getElementType();
5050  }
5051 
5052  return false;
5053 }
5054 
5055 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5056  FieldDecl *Field,
5057  IndirectFieldDecl *Indirect = nullptr) {
5058  if (Field->isInvalidDecl())
5059  return false;
5060 
5061  // Overwhelmingly common case: we have a direct initializer for this field.
5062  if (CXXCtorInitializer *Init =
5063  Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5064  return Info.addFieldInitializer(Init);
5065 
5066  // C++11 [class.base.init]p8:
5067  // if the entity is a non-static data member that has a
5068  // brace-or-equal-initializer and either
5069  // -- the constructor's class is a union and no other variant member of that
5070  // union is designated by a mem-initializer-id or
5071  // -- the constructor's class is not a union, and, if the entity is a member
5072  // of an anonymous union, no other member of that union is designated by
5073  // a mem-initializer-id,
5074  // the entity is initialized as specified in [dcl.init].
5075  //
5076  // We also apply the same rules to handle anonymous structs within anonymous
5077  // unions.
5078  if (Info.isWithinInactiveUnionMember(Field, Indirect))
5079  return false;
5080 
5081  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5082  ExprResult DIE =
5083  SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5084  if (DIE.isInvalid())
5085  return true;
5086 
5087  auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5088  SemaRef.checkInitializerLifetime(Entity, DIE.get());
5089 
5090  CXXCtorInitializer *Init;
5091  if (Indirect)
5092  Init = new (SemaRef.Context)
5093  CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5094  SourceLocation(), DIE.get(), SourceLocation());
5095  else
5096  Init = new (SemaRef.Context)
5097  CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5098  SourceLocation(), DIE.get(), SourceLocation());
5099  return Info.addFieldInitializer(Init);
5100  }
5101 
5102  // Don't initialize incomplete or zero-length arrays.
5103  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5104  return false;
5105 
5106  // Don't try to build an implicit initializer if there were semantic
5107  // errors in any of the initializers (and therefore we might be
5108  // missing some that the user actually wrote).
5109  if (Info.AnyErrorsInInits)
5110  return false;
5111 
5112  CXXCtorInitializer *Init = nullptr;
5113  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5114  Indirect, Init))
5115  return true;
5116 
5117  if (!Init)
5118  return false;
5119 
5120  return Info.addFieldInitializer(Init);
5121 }
5122 
5123 bool
5125  CXXCtorInitializer *Initializer) {
5126  assert(Initializer->isDelegatingInitializer());
5127  Constructor->setNumCtorInitializers(1);
5128  CXXCtorInitializer **initializer =
5129  new (Context) CXXCtorInitializer*[1];
5130  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5131  Constructor->setCtorInitializers(initializer);
5132 
5133  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5134  MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5135  DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5136  }
5137 
5138  DelegatingCtorDecls.push_back(Constructor);
5139 
5140  DiagnoseUninitializedFields(*this, Constructor);
5141 
5142  return false;
5143 }
5144 
5145 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5146  ArrayRef<CXXCtorInitializer *> Initializers) {
5147  if (Constructor->isDependentContext()) {
5148  // Just store the initializers as written, they will be checked during
5149  // instantiation.
5150  if (!Initializers.empty()) {
5151  Constructor->setNumCtorInitializers(Initializers.size());
5152  CXXCtorInitializer **baseOrMemberInitializers =
5153  new (Context) CXXCtorInitializer*[Initializers.size()];
5154  memcpy(baseOrMemberInitializers, Initializers.data(),
5155  Initializers.size() * sizeof(CXXCtorInitializer*));
5156  Constructor->setCtorInitializers(baseOrMemberInitializers);
5157  }
5158 
5159  // Let template instantiation know whether we had errors.
5160  if (AnyErrors)
5161  Constructor->setInvalidDecl();
5162 
5163  return false;
5164  }
5165 
5166  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5167 
5168  // We need to build the initializer AST according to order of construction
5169  // and not what user specified in the Initializers list.
5170  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5171  if (!ClassDecl)
5172  return true;
5173 
5174  bool HadError = false;
5175 
5176  for (unsigned i = 0; i < Initializers.size(); i++) {
5177  CXXCtorInitializer *Member = Initializers[i];
5178 
5179  if (Member->isBaseInitializer())
5180  Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5181  else {
5182  Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5183 
5184  if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5185  for (auto *C : F->chain()) {
5186  FieldDecl *FD = dyn_cast<FieldDecl>(C);
5187  if (FD && FD->getParent()->isUnion())
5188  Info.ActiveUnionMember.insert(std::make_pair(
5189  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5190  }
5191  } else if (FieldDecl *FD = Member->getMember()) {
5192  if (FD->getParent()->isUnion())
5193  Info.ActiveUnionMember.insert(std::make_pair(
5194  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5195  }
5196  }
5197  }
5198 
5199  // Keep track of the direct virtual bases.
5201  for (auto &I : ClassDecl->bases()) {
5202  if (I.isVirtual())
5203  DirectVBases.insert(&I);
5204  }
5205 
5206  // Push virtual bases before others.
5207  for (auto &VBase : ClassDecl->vbases()) {
5209  = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5210  // [class.base.init]p7, per DR257:
5211  // A mem-initializer where the mem-initializer-id names a virtual base
5212  // class is ignored during execution of a constructor of any class that
5213  // is not the most derived class.
5214  if (ClassDecl->isAbstract()) {
5215  // FIXME: Provide a fixit to remove the base specifier. This requires
5216  // tracking the location of the associated comma for a base specifier.
5217  Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5218  << VBase.getType() << ClassDecl;
5219  DiagnoseAbstractType(ClassDecl);
5220  }
5221 
5222  Info.AllToInit.push_back(Value);
5223  } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5224  // [class.base.init]p8, per DR257:
5225  // If a given [...] base class is not named by a mem-initializer-id
5226  // [...] and the entity is not a virtual base class of an abstract
5227  // class, then [...] the entity is default-initialized.
5228  bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5229  CXXCtorInitializer *CXXBaseInit;
5230  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5231  &VBase, IsInheritedVirtualBase,
5232  CXXBaseInit)) {
5233  HadError = true;
5234  continue;
5235  }
5236 
5237  Info.AllToInit.push_back(CXXBaseInit);
5238  }
5239  }
5240 
5241  // Non-virtual bases.
5242  for (auto &Base : ClassDecl->bases()) {
5243  // Virtuals are in the virtual base list and already constructed.
5244  if (Base.isVirtual())
5245  continue;
5246 
5248  = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5249  Info.AllToInit.push_back(Value);
5250  } else if (!AnyErrors) {
5251  CXXCtorInitializer *CXXBaseInit;
5252  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5253  &Base, /*IsInheritedVirtualBase=*/false,
5254  CXXBaseInit)) {
5255  HadError = true;
5256  continue;
5257  }
5258 
5259  Info.AllToInit.push_back(CXXBaseInit);
5260  }
5261  }
5262 
5263  // Fields.
5264  for (auto *Mem : ClassDecl->decls()) {
5265  if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5266  // C++ [class.bit]p2:
5267  // A declaration for a bit-field that omits the identifier declares an
5268  // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5269  // initialized.
5270  if (F->isUnnamedBitfield())
5271  continue;
5272 
5273  // If we're not generating the implicit copy/move constructor, then we'll
5274  // handle anonymous struct/union fields based on their individual
5275  // indirect fields.
5276  if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5277  continue;
5278 
5279  if (CollectFieldInitializer(*this, Info, F))
5280  HadError = true;
5281  continue;
5282  }
5283 
5284  // Beyond this point, we only consider default initialization.
5285  if (Info.isImplicitCopyOrMove())
5286  continue;
5287 
5288  if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5289  if (F->getType()->isIncompleteArrayType()) {
5290  assert(ClassDecl->hasFlexibleArrayMember() &&
5291  "Incomplete array type is not valid");
5292  continue;
5293  }
5294 
5295  // Initialize each field of an anonymous struct individually.
5296  if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5297  HadError = true;
5298 
5299  continue;
5300  }
5301  }
5302 
5303  unsigned NumInitializers = Info.AllToInit.size();
5304  if (NumInitializers > 0) {
5305  Constructor->setNumCtorInitializers(NumInitializers);
5306  CXXCtorInitializer **baseOrMemberInitializers =
5307  new (Context) CXXCtorInitializer*[NumInitializers];
5308  memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5309  NumInitializers * sizeof(CXXCtorInitializer*));
5310  Constructor->setCtorInitializers(baseOrMemberInitializers);
5311 
5312  // Constructors implicitly reference the base and member
5313  // destructors.
5314  MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5315  Constructor->getParent());
5316  }
5317 
5318  return HadError;
5319 }
5320 
5322  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5323  const RecordDecl *RD = RT->getDecl();
5324  if (RD->isAnonymousStructOrUnion()) {
5325  for (auto *Field : RD->fields())
5326  PopulateKeysForFields(Field, IdealInits);
5327  return;
5328  }
5329  }
5330  IdealInits.push_back(Field->getCanonicalDecl());
5331 }
5332 
5333 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5334  return Context.getCanonicalType(BaseType).getTypePtr();
5335 }
5336 
5337 static const void *GetKeyForMember(ASTContext &Context,
5338  CXXCtorInitializer *Member) {
5339  if (!Member->isAnyMemberInitializer())
5340  return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5341 
5342  return Member->getAnyMember()->getCanonicalDecl();
5343 }
5344 
5347  const CXXCtorInitializer *Current) {
5348  if (Previous->isAnyMemberInitializer())
5349  Diag << 0 << Previous->getAnyMember();
5350  else
5351  Diag << 1 << Previous->getTypeSourceInfo()->getType();
5352 
5353  if (Current->isAnyMemberInitializer())
5354  Diag << 0 << Current->getAnyMember();
5355  else
5356  Diag << 1 << Current->getTypeSourceInfo()->getType();
5357 }
5358 
5360  Sema &SemaRef, const CXXConstructorDecl *Constructor,
5362  if (Constructor->getDeclContext()->isDependentContext())
5363  return;
5364 
5365  // Don't check initializers order unless the warning is enabled at the
5366  // location of at least one initializer.
5367  bool ShouldCheckOrder = false;
5368  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5369  CXXCtorInitializer *Init = Inits[InitIndex];
5370  if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5371  Init->getSourceLocation())) {
5372  ShouldCheckOrder = true;
5373  break;
5374  }
5375  }
5376  if (!ShouldCheckOrder)
5377  return;
5378 
5379  // Build the list of bases and members in the order that they'll
5380  // actually be initialized. The explicit initializers should be in
5381  // this same order but may be missing things.
5382  SmallVector<const void*, 32> IdealInitKeys;
5383 
5384  const CXXRecordDecl *ClassDecl = Constructor->getParent();
5385 
5386  // 1. Virtual bases.
5387  for (const auto &VBase : ClassDecl->vbases())
5388  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5389 
5390  // 2. Non-virtual bases.
5391  for (const auto &Base : ClassDecl->bases()) {
5392  if (Base.isVirtual())
5393  continue;
5394  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5395  }
5396 
5397  // 3. Direct fields.
5398  for (auto *Field : ClassDecl->fields()) {
5399  if (Field->isUnnamedBitfield())
5400  continue;
5401 
5402  PopulateKeysForFields(Field, IdealInitKeys);
5403  }
5404 
5405  unsigned NumIdealInits = IdealInitKeys.size();
5406  unsigned IdealIndex = 0;
5407 
5408  // Track initializers that are in an incorrect order for either a warning or
5409  // note if multiple ones occur.
5410  SmallVector<unsigned> WarnIndexes;
5411  // Correlates the index of an initializer in the init-list to the index of
5412  // the field/base in the class.
5413  SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5414 
5415  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5416  const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5417 
5418  // Scan forward to try to find this initializer in the idealized
5419  // initializers list.
5420  for (; IdealIndex != NumIdealInits; ++IdealIndex)
5421  if (InitKey == IdealInitKeys[IdealIndex])
5422  break;
5423 
5424  // If we didn't find this initializer, it must be because we
5425  // scanned past it on a previous iteration. That can only
5426  // happen if we're out of order; emit a warning.
5427  if (IdealIndex == NumIdealInits && InitIndex) {
5428  WarnIndexes.push_back(InitIndex);
5429 
5430  // Move back to the initializer's location in the ideal list.
5431  for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5432  if (InitKey == IdealInitKeys[IdealIndex])
5433  break;
5434 
5435  assert(IdealIndex < NumIdealInits &&
5436  "initializer not found in initializer list");
5437  }
5438  CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5439  }
5440 
5441  if (WarnIndexes.empty())
5442  return;
5443 
5444  // Sort based on the ideal order, first in the pair.
5445  llvm::sort(CorrelatedInitOrder,
5446  [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5447 
5448  // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5449  // emit the diagnostic before we can try adding notes.
5450  {
5451  Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5452  Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5453  WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5454  : diag::warn_some_initializers_out_of_order);
5455 
5456  for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5457  if (CorrelatedInitOrder[I].second == I)
5458  continue;
5459  // Ideally we would be using InsertFromRange here, but clang doesn't
5460  // appear to handle InsertFromRange correctly when the source range is
5461  // modified by another fix-it.
5463  Inits[I]->getSourceRange(),
5466  Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5467  SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5468  }
5469 
5470  // If there is only 1 item out of order, the warning expects the name and
5471  // type of each being added to it.
5472  if (WarnIndexes.size() == 1) {
5473  AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5474  Inits[WarnIndexes.front()]);
5475  return;
5476  }
5477  }
5478  // More than 1 item to warn, create notes letting the user know which ones
5479  // are bad.
5480  for (unsigned WarnIndex : WarnIndexes) {
5481  const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5482  auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5483  diag::note_initializer_out_of_order);
5484  AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5485  D << PrevInit->getSourceRange();
5486  }
5487 }
5488 
5489 namespace {
5490 bool CheckRedundantInit(Sema &S,
5491  CXXCtorInitializer *Init,
5492  CXXCtorInitializer *&PrevInit) {
5493  if (!PrevInit) {
5494  PrevInit = Init;
5495  return false;
5496  }
5497 
5498  if (FieldDecl *Field = Init->getAnyMember())
5499  S.Diag(Init->getSourceLocation(),
5500  diag::err_multiple_mem_initialization)
5501  << Field->getDeclName()
5502  << Init->getSourceRange();
5503  else {
5504  const Type *BaseClass = Init->getBaseClass();
5505  assert(BaseClass && "neither field nor base");
5506  S.Diag(Init->getSourceLocation(),
5507  diag::err_multiple_base_initialization)
5508  << QualType(BaseClass, 0)
5509  << Init->getSourceRange();
5510  }
5511  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5512  << 0 << PrevInit->getSourceRange();
5513 
5514  return true;
5515 }
5516 
5517 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5518 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5519 
5520 bool CheckRedundantUnionInit(Sema &S,
5521  CXXCtorInitializer *Init,
5522  RedundantUnionMap &Unions) {
5523  FieldDecl *Field = Init->getAnyMember();
5524  RecordDecl *Parent = Field->getParent();
5525  NamedDecl *Child = Field;
5526 
5527  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5528  if (Parent->isUnion()) {
5529  UnionEntry &En = Unions[Parent];
5530  if (En.first && En.first != Child) {
5531  S.Diag(Init->getSourceLocation(),
5532  diag::err_multiple_mem_union_initialization)
5533  << Field->getDeclName()
5534  << Init->getSourceRange();
5535  S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5536  << 0 << En.second->getSourceRange();
5537  return true;
5538  }
5539  if (!En.first) {
5540  En.first = Child;
5541  En.second = Init;
5542  }
5543  if (!Parent->isAnonymousStructOrUnion())
5544  return false;
5545  }
5546 
5547  Child = Parent;
5548  Parent = cast<RecordDecl>(Parent->getDeclContext());
5549  }
5550 
5551  return false;
5552 }
5553 } // namespace
5554 
5555 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5556 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5557  SourceLocation ColonLoc,
5559  bool AnyErrors) {
5560  if (!ConstructorDecl)
5561  return;
5562 
5563  AdjustDeclIfTemplate(ConstructorDecl);
5564 
5565  CXXConstructorDecl *Constructor
5566  = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5567 
5568  if (!Constructor) {
5569  Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5570  return;
5571  }
5572 
5573  // Mapping for the duplicate initializers check.
5574  // For member initializers, this is keyed with a FieldDecl*.
5575  // For base initializers, this is keyed with a Type*.
5576  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5577 
5578  // Mapping for the inconsistent anonymous-union initializers check.
5579  RedundantUnionMap MemberUnions;
5580 
5581  bool HadError = false;
5582  for (unsigned i = 0; i < MemInits.size(); i++) {
5583  CXXCtorInitializer *Init = MemInits[i];
5584 
5585  // Set the source order index.
5586  Init->setSourceOrder(i);
5587 
5588  if (Init->isAnyMemberInitializer()) {
5589  const void *Key = GetKeyForMember(Context, Init);
5590  if (CheckRedundantInit(*this, Init, Members[Key]) ||
5591  CheckRedundantUnionInit(*this, Init, MemberUnions))
5592  HadError = true;
5593  } else if (Init->isBaseInitializer()) {
5594  const void *Key = GetKeyForMember(Context, Init);
5595  if (CheckRedundantInit(*this, Init, Members[Key]))
5596  HadError = true;
5597  } else {
5598  assert(Init->isDelegatingInitializer());
5599  // This must be the only initializer
5600  if (MemInits.size() != 1) {
5601  Diag(Init->getSourceLocation(),
5602  diag::err_delegating_initializer_alone)
5603  << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5604  // We will treat this as being the only initializer.
5605  }
5606  SetDelegatingInitializer(Constructor, MemInits[i]);
5607  // Return immediately as the initializer is set.
5608  return;
5609  }
5610  }
5611 
5612  if (HadError)
5613  return;
5614 
5615  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5616 
5617  SetCtorInitializers(Constructor, AnyErrors, MemInits);
5618 
5619  DiagnoseUninitializedFields(*this, Constructor);
5620 }
5621 
5622 void
5624  CXXRecordDecl *ClassDecl) {
5625  // Ignore dependent contexts. Also ignore unions, since their members never
5626  // have destructors implicitly called.
5627  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5628  return;
5629 
5630  // FIXME: all the access-control diagnostics are positioned on the
5631  // field/base declaration. That's probably good; that said, the
5632  // user might reasonably want to know why the destructor is being
5633  // emitted, and we currently don't say.
5634 
5635  // Non-static data members.
5636  for (auto *Field : ClassDecl->fields()) {
5637  if (Field->isInvalidDecl())
5638  continue;
5639 
5640  // Don't destroy incomplete or zero-length arrays.
5641  if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5642  continue;
5643 
5644  QualType FieldType = Context.getBaseElementType(Field->getType());
5645 
5646  const RecordType* RT = FieldType->getAs<RecordType>();
5647  if (!RT)
5648  continue;
5649 
5650  CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5651  if (FieldClassDecl->isInvalidDecl())
5652  continue;
5653  if (FieldClassDecl->hasIrrelevantDestructor())
5654  continue;
5655  // The destructor for an implicit anonymous union member is never invoked.
5656  if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5657  continue;
5658 
5659  CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5660  assert(Dtor && "No dtor found for FieldClassDecl!");
5661  CheckDestructorAccess(Field->getLocation(), Dtor,
5662  PDiag(diag::err_access_dtor_field)
5663  << Field->getDeclName()
5664  << FieldType);
5665 
5666  MarkFunctionReferenced(Location, Dtor);
5667  DiagnoseUseOfDecl(Dtor, Location);
5668  }
5669 
5670  // We only potentially invoke the destructors of potentially constructed
5671  // subobjects.
5672  bool VisitVirtualBases = !ClassDecl->isAbstract();
5673 
5674  // If the destructor exists and has already been marked used in the MS ABI,
5675  // then virtual base destructors have already been checked and marked used.
5676  // Skip checking them again to avoid duplicate diagnostics.
5678  CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5679  if (Dtor && Dtor->isUsed())
5680  VisitVirtualBases = false;
5681  }
5682 
5683  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5684 
5685  // Bases.
5686  for (const auto &Base : ClassDecl->bases()) {
5687  const RecordType *RT = Base.getType()->getAs<RecordType>();
5688  if (!RT)
5689  continue;
5690 
5691  // Remember direct virtual bases.
5692  if (Base.isVirtual()) {
5693  if (!VisitVirtualBases)
5694  continue;
5695  DirectVirtualBases.insert(RT);
5696  }
5697 
5698  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5699  // If our base class is invalid, we probably can't get its dtor anyway.
5700  if (BaseClassDecl->isInvalidDecl())
5701  continue;
5702  if (BaseClassDecl->hasIrrelevantDestructor())
5703  continue;
5704 
5705  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5706  assert(Dtor && "No dtor found for BaseClassDecl!");
5707 
5708  // FIXME: caret should be on the start of the class name
5709  CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5710  PDiag(diag::err_access_dtor_base)
5711  << Base.getType() << Base.getSourceRange(),
5712  Context.getTypeDeclType(ClassDecl));
5713 
5714  MarkFunctionReferenced(Location, Dtor);
5715  DiagnoseUseOfDecl(Dtor, Location);
5716  }
5717 
5718  if (VisitVirtualBases)
5719  MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5720  &DirectVirtualBases);
5721 }
5722 
5724  SourceLocation Location, CXXRecordDecl *ClassDecl,
5725  llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5726  // Virtual bases.
5727  for (const auto &VBase : ClassDecl->vbases()) {
5728  // Bases are always records in a well-formed non-dependent class.
5729  const RecordType *RT = VBase.getType()->castAs<RecordType>();
5730 
5731  // Ignore already visited direct virtual bases.
5732  if (DirectVirtualBases && DirectVirtualBases->count(RT))
5733  continue;
5734 
5735  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5736  // If our base class is invalid, we probably can't get its dtor anyway.
5737  if (BaseClassDecl->isInvalidDecl())
5738  continue;
5739  if (BaseClassDecl->hasIrrelevantDestructor())
5740  continue;
5741 
5742  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5743  assert(Dtor && "No dtor found for BaseClassDecl!");
5745  ClassDecl->getLocation(), Dtor,
5746  PDiag(diag::err_access_dtor_vbase)
5747  << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5748  Context.getTypeDeclType(ClassDecl)) ==
5749  AR_accessible) {
5751  Context.getTypeDeclType(ClassDecl), VBase.getType(),
5752  diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5753  SourceRange(), DeclarationName(), nullptr);
5754  }
5755 
5756  MarkFunctionReferenced(Location, Dtor);
5757  DiagnoseUseOfDecl(Dtor, Location);
5758  }
5759 }
5760 
5762  if (!CDtorDecl)
5763  return;
5764 
5765  if (CXXConstructorDecl *Constructor
5766  = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5767  SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5768  DiagnoseUninitializedFields(*this, Constructor);
5769  }
5770 }
5771 
5773  if (!getLangOpts().CPlusPlus)
5774  return false;
5775 
5776  const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5777  if (!RD)
5778  return false;
5779 
5780  // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5781  // class template specialization here, but doing so breaks a lot of code.
5782 
5783  // We can't answer whether something is abstract until it has a
5784  // definition. If it's currently being defined, we'll walk back
5785  // over all the declarations when we have a full definition.
5786  const CXXRecordDecl *Def = RD->getDefinition();
5787  if (!Def || Def->isBeingDefined())
5788  return false;
5789 
5790  return RD->isAbstract();
5791 }
5792 
5794  TypeDiagnoser &Diagnoser) {
5795  if (!isAbstractType(Loc, T))
5796  return false;
5797 
5798  T = Context.getBaseElementType(T);
5799  Diagnoser.diagnose(*this, Loc, T);
5801  return true;
5802 }
5803 
5805  // Check if we've already emitted the list of pure virtual functions
5806  // for this class.
5808  return;
5809 
5810  // If the diagnostic is suppressed, don't emit the notes. We're only
5811  // going to emit them once, so try to attach them to a diagnostic we're
5812  // actually going to show.
5814  return;
5815 
5816  CXXFinalOverriderMap FinalOverriders;
5817  RD->getFinalOverriders(FinalOverriders);
5818 
5819  // Keep a set of seen pure methods so we won't diagnose the same method
5820  // more than once.
5822 
5823  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5824  MEnd = FinalOverriders.end();
5825  M != MEnd;
5826  ++M) {
5827  for (OverridingMethods::iterator SO = M->second.begin(),
5828  SOEnd = M->second.end();
5829  SO != SOEnd; ++SO) {
5830  // C++ [class.abstract]p4:
5831  // A class is abstract if it contains or inherits at least one
5832  // pure virtual function for which the final overrider is pure
5833  // virtual.
5834 
5835  //
5836  if (SO->second.size() != 1)
5837  continue;
5838 
5839  if (!SO->second.front().Method->isPure())
5840  continue;
5841 
5842  if (!SeenPureMethods.insert(SO->second.front().Method).second)
5843  continue;
5844 
5845  Diag(SO->second.front().Method->getLocation(),
5846  diag::note_pure_virtual_function)
5847  << SO->second.front().Method->getDeclName() << RD->getDeclName();
5848  }
5849  }
5850 
5853  PureVirtualClassDiagSet->insert(RD);
5854 }
5855 
5856 namespace {
5857 struct AbstractUsageInfo {
5858  Sema &S;
5859  CXXRecordDecl *Record;
5860  CanQualType AbstractType;
5861  bool Invalid;
5862 
5863  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5864  : S(S), Record(Record),
5865  AbstractType(S.Context.getCanonicalType(
5866  S.Context.getTypeDeclType(Record))),
5867  Invalid(false) {}
5868 
5869  void DiagnoseAbstractType() {
5870  if (Invalid) return;
5871  S.DiagnoseAbstractType(Record);
5872  Invalid = true;
5873  }
5874 
5875  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5876 };
5877 
5878 struct CheckAbstractUsage {
5879  AbstractUsageInfo &Info;
5880  const NamedDecl *Ctx;
5881 
5882  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5883  : Info(Info), Ctx(Ctx) {}
5884 
5885  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5886  switch (TL.getTypeLocClass()) {
5887 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5888 #define TYPELOC(CLASS, PARENT) \
5889  case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5890 #include "clang/AST/TypeLocNodes.def"
5891  }
5892  }
5893 
5894  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5896  for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5897  if (!TL.getParam(I))
5898  continue;
5899 
5900  TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5901  if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5902  }
5903  }
5904 
5905  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5907  }
5908 
5910  // Visit the type parameters from a permissive context.
5911  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5912  TemplateArgumentLoc TAL = TL.getArgLoc(I);
5914  if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5915  Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5916  // TODO: other template argument types?
5917  }
5918  }
5919 
5920  // Visit pointee types from a permissive context.
5921 #define CheckPolymorphic(Type) \
5922  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5923  Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5924  }
5930 
5931  /// Handle all the types we haven't given a more specific
5932  /// implementation for above.
5933  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5934  // Every other kind of type that we haven't called out already
5935  // that has an inner type is either (1) sugar or (2) contains that
5936  // inner type in some way as a subobject.
5937  if (TypeLoc Next = TL.getNextTypeLoc())
5938  return Visit(Next, Sel);
5939 
5940  // If there's no inner type and we're in a permissive context,
5941  // don't diagnose.
5942  if (Sel == Sema::AbstractNone) return;
5943 
5944  // Check whether the type matches the abstract type.
5945  QualType T = TL.getType();
5946  if (T->isArrayType()) {
5948  T = Info.S.Context.getBaseElementType(T);
5949  }
5951  if (CT != Info.AbstractType) return;
5952 
5953  // It matched; do some magic.
5954  // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5955  if (Sel == Sema::AbstractArrayType) {
5956  Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5957  << T << TL.getSourceRange();
5958  } else {
5959  Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5960  << Sel << T << TL.getSourceRange();
5961  }
5962  Info.DiagnoseAbstractType();
5963  }
5964 };
5965 
5966 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5968  CheckAbstractUsage(*this, D).Visit(TL, Sel);
5969 }
5970 
5971 }
5972 
5973 /// Check for invalid uses of an abstract type in a function declaration.
5974 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5975  FunctionDecl *FD) {
5976  // No need to do the check on definitions, which require that
5977  // the return/param types be complete.
5978  if (FD->doesThisDeclarationHaveABody())
5979  return;
5980 
5981  // For safety's sake, just ignore it if we don't have type source
5982  // information. This should never happen for non-implicit methods,
5983  // but...
5984  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5985  Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5986 }
5987 
5988 /// Check for invalid uses of an abstract type in a variable0 declaration.
5989 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5990  VarDecl *VD) {
5991  // No need to do the check on definitions, which require that
5992  // the type is complete.
5993  if (VD->isThisDeclarationADefinition())
5994  return;
5995 
5996  Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5998 }
5999 
6000 /// Check for invalid uses of an abstract type within a class definition.
6001 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6002  CXXRecordDecl *RD) {
6003  for (auto *D : RD->decls()) {
6004  if (D->isImplicit()) continue;
6005 
6006  // Step through friends to the befriended declaration.
6007  if (auto *FD = dyn_cast<FriendDecl>(D)) {
6008  D = FD->getFriendDecl();
6009  if (!D) continue;
6010  }
6011 
6012  // Functions and function templates.
6013  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6014  CheckAbstractClassUsage(Info, FD);
6015  } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6016  CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6017 
6018  // Fields and static variables.
6019  } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6020  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6021  Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6022  } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6023  CheckAbstractClassUsage(Info, VD);
6024  } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6025  CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6026 
6027  // Nested classes and class templates.
6028  } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6029  CheckAbstractClassUsage(Info, RD);
6030  } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6031  CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6032  }
6033  }
6034 }
6035 
6037  Attr *ClassAttr = getDLLAttr(Class);
6038  if (!ClassAttr)
6039  return;
6040 
6041  assert(ClassAttr->getKind() == attr::DLLExport);
6042 
6043  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6044 
6046  // Don't go any further if this is just an explicit instantiation
6047  // declaration.
6048  return;
6049 
6050  // Add a context note to explain how we got to any diagnostics produced below.
6051  struct MarkingClassDllexported {
6052  Sema &S;
6053  MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6054  SourceLocation AttrLoc)
6055  : S(S) {
6058  Ctx.PointOfInstantiation = AttrLoc;
6059  Ctx.Entity = Class;
6060  S.pushCodeSynthesisContext(Ctx);
6061  }
6062  ~MarkingClassDllexported() {
6064  }
6065  } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6066 
6067  if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6068  S.MarkVTableUsed(Class->getLocation(), Class, true);
6069 
6070  for (Decl *Member : Class->decls()) {
6071  // Skip members that were not marked exported.
6072  if (!Member->hasAttr<DLLExportAttr>())
6073  continue;
6074 
6075  // Defined static variables that are members of an exported base
6076  // class must be marked export too.
6077  auto *VD = dyn_cast<VarDecl>(Member);
6078  if (VD && VD->getStorageClass() == SC_Static &&
6080  S.MarkVariableReferenced(VD->getLocation(), VD);
6081 
6082  auto *MD = dyn_cast<CXXMethodDecl>(Member);
6083  if (!MD)
6084  continue;
6085 
6086  if (MD->isUserProvided()) {
6087  // Instantiate non-default class member functions ...
6088 
6089  // .. except for certain kinds of template specializations.
6090  if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6091  continue;
6092 
6093  // If this is an MS ABI dllexport default constructor, instantiate any
6094  // default arguments.
6096  auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6097  if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6099  }
6100  }
6101 
6102  S.MarkFunctionReferenced(Class->getLocation(), MD);
6103 
6104  // The function will be passed to the consumer when its definition is
6105  // encountered.
6106  } else if (MD->isExplicitlyDefaulted()) {
6107  // Synthesize and instantiate explicitly defaulted methods.
6108  S.MarkFunctionReferenced(Class->getLocation(), MD);
6109 
6111  // Except for explicit instantiation defs, we will not see the
6112  // definition again later, so pass it to the consumer now.
6114  }
6115  } else if (!MD->isTrivial() ||
6116  MD->isCopyAssignmentOperator() ||
6117  MD->isMoveAssignmentOperator()) {
6118  // Synthesize and instantiate non-trivial implicit methods, and the copy
6119  // and move assignment operators. The latter are exported even if they
6120  // are trivial, because the address of an operator can be taken and
6121  // should compare equal across libraries.
6122  S.MarkFunctionReferenced(Class->getLocation(), MD);
6123 
6124  // There is no later point when we will see the definition of this
6125  // function, so pass it to the consumer now.
6127  }
6128  }
6129 }
6130 
6132  CXXRecordDecl *Class) {
6133  // Only the MS ABI has default constructor closures, so we don't need to do
6134  // this semantic checking anywhere else.
6136  return;
6137 
6138  CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6139  for (Decl *Member : Class->decls()) {
6140  // Look for exported default constructors.
6141  auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6142  if (!CD || !CD->isDefaultConstructor())
6143  continue;
6144  auto *Attr = CD->getAttr<DLLExportAttr>();
6145  if (!Attr)
6146  continue;
6147 
6148  // If the class is non-dependent, mark the default arguments as ODR-used so
6149  // that we can properly codegen the constructor closure.
6150  if (!Class->isDependentContext()) {
6151  for (ParmVarDecl *PD : CD->parameters()) {
6152  (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6154  }
6155  }
6156 
6157  if (LastExportedDefaultCtor) {
6158  S.Diag(LastExportedDefaultCtor->getLocation(),
6159  diag::err_attribute_dll_ambiguous_default_ctor)
6160  << Class;
6161  S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6162  << CD->getDeclName();
6163  return;
6164  }
6165  LastExportedDefaultCtor = CD;
6166  }
6167 }
6168 
6170  CXXRecordDecl *Class) {
6171  bool ErrorReported = false;
6172  auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6173  ClassTemplateDecl *TD) {
6174  if (ErrorReported)
6175  return;
6176  S.Diag(TD->getLocation(),
6177  diag::err_cuda_device_builtin_surftex_cls_template)
6178  << /*surface*/ 0 << TD;
6179  ErrorReported = true;
6180  };
6181 
6182  ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6183  if (!TD) {
6184  auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6185  if (!SD) {
6186  S.Diag(Class->getLocation(),
6187  diag::err_cuda_device_builtin_surftex_ref_decl)
6188  << /*surface*/ 0 << Class;
6189  S.Diag(Class->getLocation(),
6190  diag::note_cuda_device_builtin_surftex_should_be_template_class)
6191  << Class;
6192  return;
6193  }
6194  TD = SD->getSpecializedTemplate();
6195  }
6196 
6198  unsigned N = Params->size();
6199 
6200  if (N != 2) {
6201  reportIllegalClassTemplate(S, TD);
6202  S.Diag(TD->getLocation(),
6203  diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6204  << TD << 2;
6205  }
6206  if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6207  reportIllegalClassTemplate(S, TD);
6208  S.Diag(TD->getLocation(),
6209  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6210  << TD << /*1st*/ 0 << /*type*/ 0;
6211  }
6212  if (N > 1) {
6213  auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6214  if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6215  reportIllegalClassTemplate(S, TD);
6216  S.Diag(TD->getLocation(),
6217  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6218  << TD << /*2nd*/ 1 << /*integer*/ 1;
6219  }
6220  }
6221 }
6222 
6224  CXXRecordDecl *Class) {
6225  bool ErrorReported = false;
6226  auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6227  ClassTemplateDecl *TD) {
6228  if (ErrorReported)
6229  return;
6230  S.Diag(TD->getLocation(),
6231  diag::err_cuda_device_builtin_surftex_cls_template)
6232  << /*texture*/ 1 << TD;
6233  ErrorReported = true;
6234  };
6235 
6236  ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6237  if (!TD) {
6238  auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6239  if (!SD) {
6240  S.Diag(Class->getLocation(),
6241  diag::err_cuda_device_builtin_surftex_ref_decl)
6242  << /*texture*/ 1 << Class;
6243  S.Diag(Class->getLocation(),
6244  diag::note_cuda_device_builtin_surftex_should_be_template_class)
6245  << Class;
6246  return;
6247  }
6248  TD = SD->getSpecializedTemplate();
6249  }
6250 
6252  unsigned N = Params->size();
6253 
6254  if (N != 3) {
6255  reportIllegalClassTemplate(S, TD);
6256  S.Diag(TD->getLocation(),
6257  diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6258  << TD << 3;
6259  }
6260  if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6261  reportIllegalClassTemplate(S, TD);
6262  S.Diag(TD->getLocation(),
6263  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6264  << TD << /*1st*/ 0 << /*type*/ 0;
6265  }
6266  if (N > 1) {
6267  auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6268  if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6269  reportIllegalClassTemplate(S, TD);
6270  S.Diag(TD->getLocation(),
6271  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6272  << TD << /*2nd*/ 1 << /*integer*/ 1;
6273  }
6274  }
6275  if (N > 2) {
6276  auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6277  if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6278  reportIllegalClassTemplate(S, TD);
6279  S.Diag(TD->getLocation(),
6280  diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6281  << TD << /*3rd*/ 2 << /*integer*/ 1;
6282  }
6283  }
6284 }
6285 
6287  // Mark any compiler-generated routines with the implicit code_seg attribute.
6288  for (auto *Method : Class->methods()) {
6289  if (Method->isUserProvided())
6290  continue;
6291  if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6292  Method->addAttr(A);
6293  }
6294 }
6295 
6296 /// Check class-level dllimport/dllexport attribute.
6298  Attr *ClassAttr = getDLLAttr(Class);
6299 
6300  // MSVC inherits DLL attributes to partial class template specializations.
6301  if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6302  if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6303  if (Attr *TemplateAttr =
6304  getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6305  auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6306  A->setInherited(true);
6307  ClassAttr = A;
6308  }
6309  }
6310  }
6311 
6312  if (!ClassAttr)
6313  return;
6314 
6315  if (!Class->isExternallyVisible()) {
6316  Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6317  << Class << ClassAttr;
6318  return;
6319  }
6320 
6322  !ClassAttr->isInherited()) {
6323  // Diagnose dll attributes on members of class with dll attribute.
6324  for (Decl *Member : Class->decls()) {
6325  if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6326  continue;
6327  InheritableAttr *MemberAttr = getDLLAttr(Member);
6328  if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6329  continue;
6330 
6331  Diag(MemberAttr->getLocation(),
6332  diag::err_attribute_dll_member_of_dll_class)
6333  << MemberAttr << ClassAttr;
6334  Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6335  Member->setInvalidDecl();
6336  }
6337  }
6338 
6339  if (Class->getDescribedClassTemplate())
6340  // Don't inherit dll attribute until the template is instantiated.
6341  return;
6342 
6343  // The class is either imported or exported.
6344  const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6345 
6346  // Check if this was a dllimport attribute propagated from a derived class to
6347  // a base class template specialization. We don't apply these attributes to
6348  // static data members.
6349  const bool PropagatedImport =
6350  !ClassExported &&
6351  cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6352 
6353  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6354 
6355  // Ignore explicit dllexport on explicit class template instantiation
6356  // declarations, except in MinGW mode.
6357  if (ClassExported && !ClassAttr->isInherited() &&
6359  !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6360  Class->dropAttr<DLLExportAttr>();
6361  return;
6362  }
6363 
6364  // Force declaration of implicit members so they can inherit the attribute.
6366 
6367  // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6368  // seem to be true in practice?
6369 
6370  for (Decl *Member : Class->decls()) {
6371  VarDecl *VD = dyn_cast<VarDecl>(Member);
6372  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6373 
6374  // Only methods and static fields inherit the attributes.
6375  if (!VD && !MD)
6376  continue;
6377 
6378  if (MD) {
6379  // Don't process deleted methods.
6380  if (MD->isDeleted())
6381  continue;
6382 
6383  if (MD->isInlined()) {
6384  // MinGW does not import or export inline methods. But do it for
6385  // template instantiations.
6389  continue;
6390 
6391  // MSVC versions before 2015 don't export the move assignment operators
6392  // and move constructor, so don't attempt to import/export them if
6393  // we have a definition.
6394  auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6395  if ((MD->isMoveAssignmentOperator() ||
6396  (Ctor && Ctor->isMoveConstructor())) &&
6397  !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6398  continue;
6399 
6400  // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6401  // operator is exported anyway.
6402  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6403  (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6404  continue;
6405  }
6406  }
6407 
6408  // Don't apply dllimport attributes to static data members of class template
6409  // instantiations when the attribute is propagated from a derived class.
6410  if (VD && PropagatedImport)
6411  continue;
6412 
6413  if (!cast<NamedDecl>(Member)->isExternallyVisible())
6414  continue;
6415 
6416  if (!getDLLAttr(Member)) {
6417  InheritableAttr *NewAttr = nullptr;
6418 
6419  // Do not export/import inline function when -fno-dllexport-inlines is
6420  // passed. But add attribute for later local static var check.
6421  if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6424  if (ClassExported) {
6425  NewAttr = ::new (getASTContext())
6426  DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6427  } else {
6428  NewAttr = ::new (getASTContext())
6429  DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6430  }
6431  } else {
6432  NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6433  }
6434 
6435  NewAttr->setInherited(true);
6436  Member->addAttr(NewAttr);
6437 
6438  if (MD) {
6439  // Propagate DLLAttr to friend re-declarations of MD that have already
6440  // been constructed.
6441  for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6442  FD = FD->getPreviousDecl()) {
6443  if (FD->getFriendObjectKind() == Decl::FOK_None)
6444  continue;
6445  assert(!getDLLAttr(FD) &&
6446  "friend re-decl should not already have a DLLAttr");
6447  NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6448  NewAttr->setInherited(true);
6449  FD->addAttr(NewAttr);
6450  }
6451  }
6452  }
6453  }
6454 
6455  if (ClassExported)
6456  DelayedDllExportClasses.push_back(Class);
6457 }
6458 
6459 /// Perform propagation of DLL attributes from a derived class to a
6460 /// templated base class for MS compatibility.
6462  CXXRecordDecl *Class, Attr *ClassAttr,
6463  ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6464  if (getDLLAttr(
6465  BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6466  // If the base class template has a DLL attribute, don't try to change it.
6467  return;
6468  }
6469 
6470  auto TSK = BaseTemplateSpec->getSpecializationKind();
6471  if (!getDLLAttr(BaseTemplateSpec) &&
6473  TSK == TSK_ImplicitInstantiation)) {
6474  // The template hasn't been instantiated yet (or it has, but only as an
6475  // explicit instantiation declaration or implicit instantiation, which means
6476  // we haven't codegenned any members yet), so propagate the attribute.
6477  auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6478  NewAttr->setInherited(true);
6479  BaseTemplateSpec->addAttr(NewAttr);
6480 
6481  // If this was an import, mark that we propagated it from a derived class to
6482  // a base class template specialization.
6483  if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6484  ImportAttr->setPropagatedToBaseTemplate();
6485 
6486  // If the template is already instantiated, checkDLLAttributeRedeclaration()
6487  // needs to be run again to work see the new attribute. Otherwise this will
6488  // get run whenever the template is instantiated.
6489  if (TSK != TSK_Undeclared)
6490  checkClassLevelDLLAttribute(BaseTemplateSpec);
6491 
6492  return;
6493  }
6494 
6495  if (getDLLAttr(BaseTemplateSpec)) {
6496  // The template has already been specialized or instantiated with an
6497  // attribute, explicitly or through propagation. We should not try to change
6498  // it.
6499  return;
6500  }
6501 
6502  // The template was previously instantiated or explicitly specialized without
6503  // a dll attribute, It's too late for us to add an attribute, so warn that
6504  // this is unsupported.
6505  Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6506  << BaseTemplateSpec->isExplicitSpecialization();
6507  Diag(ClassAttr->getLocation(), diag::note_attribute);
6508  if (BaseTemplateSpec->isExplicitSpecialization()) {
6509  Diag(BaseTemplateSpec->getLocation(),
6510  diag::note_template_class_explicit_specialization_was_here)
6511  << BaseTemplateSpec;
6512  } else {
6513  Diag(BaseTemplateSpec->getPointOfInstantiation(),
6514  diag::note_template_class_instantiation_was_here)
6515  << BaseTemplateSpec;
6516  }
6517 }
6518 
6519 /// Determine the kind of defaulting that would be done for a given function.
6520 ///
6521 /// If the function is both a default constructor and a copy / move constructor
6522 /// (due to having a default argument for the first parameter), this picks
6523 /// CXXDefaultConstructor.
6524 ///
6525 /// FIXME: Check that case is properly handled by all callers.
6528  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6529  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6530  if (Ctor->isDefaultConstructor())
6532 
6533  if (Ctor->isCopyConstructor())
6534  return Sema::CXXCopyConstructor;
6535 
6536  if (Ctor->isMoveConstructor())
6537  return Sema::CXXMoveConstructor;
6538  }
6539 
6540  if (MD->isCopyAssignmentOperator())
6541  return Sema::CXXCopyAssignment;
6542 
6543  if (MD->isMoveAssignmentOperator())
6544  return Sema::CXXMoveAssignment;
6545 
6546  if (isa<CXXDestructorDecl>(FD))
6547  return Sema::CXXDestructor;
6548  }
6549 
6550  switch (FD->getDeclName().getCXXOverloadedOperator()) {
6551  case OO_EqualEqual:
6553 
6554  case OO_ExclaimEqual:
6556 
6557  case OO_Spaceship:
6558  // No point allowing this if <=> doesn't exist in the current language mode.
6559  if (!getLangOpts().CPlusPlus20)
6560  break;
6562 
6563  case OO_Less:
6564  case OO_LessEqual:
6565  case OO_Greater:
6566  case OO_GreaterEqual:
6567  // No point allowing this if <=> doesn't exist in the current language mode.
6568  if (!getLangOpts().CPlusPlus20)
6569  break;
6571 
6572  default:
6573  break;
6574  }
6575 
6576  // Not defaultable.
6577  return DefaultedFunctionKind();
6578 }
6579 
6581  SourceLocation DefaultLoc) {
6583  if (DFK.isComparison())
6584  return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6585 
6586  switch (DFK.asSpecialMember()) {
6588  S.DefineImplicitDefaultConstructor(DefaultLoc,
6589  cast<CXXConstructorDecl>(FD));
6590  break;
6592  S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6593  break;
6595  S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6596  break;
6597  case Sema::CXXDestructor:
6598  S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6599  break;
6601  S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6602  break;
6604  S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6605  break;
6606  case Sema::CXXInvalid:
6607  llvm_unreachable("Invalid special member.");
6608  }
6609 }
6610 
6611 /// Determine whether a type is permitted to be passed or returned in
6612 /// registers, per C++ [class.temporary]p3.
6615  if (D->isDependentType() || D->isInvalidDecl())
6616  return false;
6617 
6618  // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6619  // The PS4 platform ABI follows the behavior of Clang 3.2.
6620  if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6621  return !D->hasNonTrivialDestructorForCall() &&
6623 
6624  if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6625  bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6626  bool DtorIsTrivialForCall = false;
6627 
6628  // If a class has at least one non-deleted, trivial copy constructor, it
6629  // is passed according to the C ABI. Otherwise, it is passed indirectly.
6630  //
6631  // Note: This permits classes with non-trivial copy or move ctors to be
6632  // passed in registers, so long as they *also* have a trivial copy ctor,
6633  // which is non-conforming.
6634  if (D->needsImplicitCopyConstructor()) {
6636  if (D->hasTrivialCopyConstructor())
6637  CopyCtorIsTrivial = true;
6639  CopyCtorIsTrivialForCall = true;
6640  }
6641  } else {
6642  for (const CXXConstructorDecl *CD : D->ctors()) {
6643  if (CD->isCopyConstructor() && !CD->isDeleted()) {
6644  if (CD->isTrivial())
6645  CopyCtorIsTrivial = true;
6646  if (CD->isTrivialForCall())
6647  CopyCtorIsTrivialForCall = true;
6648  }
6649  }
6650  }
6651 
6652  if (D->needsImplicitDestructor()) {
6653  if (!D->defaultedDestructorIsDeleted() &&
6655  DtorIsTrivialForCall = true;
6656  } else if (const auto *DD = D->getDestructor()) {
6657  if (!DD->isDeleted() && DD->isTrivialForCall())
6658  DtorIsTrivialForCall = true;
6659  }
6660 
6661  // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6662  if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6663  return true;
6664 
6665  // If a class has a destructor, we'd really like to pass it indirectly
6666  // because it allows us to elide copies. Unfortunately, MSVC makes that
6667  // impossible for small types, which it will pass in a single register or
6668  // stack slot. Most objects with dtors are large-ish, so handle that early.
6669  // We can't call out all large objects as being indirect because there are
6670  // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6671  // how we pass large POD types.
6672 
6673  // Note: This permits small classes with nontrivial destructors to be
6674  // passed in registers, which is non-conforming.
6675  bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6676  uint64_t TypeSize = isAArch64 ? 128 : 64;
6677 
6678  if (CopyCtorIsTrivial &&
6679  S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6680  return true;
6681  return false;
6682  }
6683 
6684  // Per C++ [class.temporary]p3, the relevant condition is:
6685  // each copy constructor, move constructor, and destructor of X is
6686  // either trivial or deleted, and X has at least one non-deleted copy
6687  // or move constructor
6688  bool HasNonDeletedCopyOrMove = false;
6689 
6690  if (D->needsImplicitCopyConstructor() &&
6693  return false;
6694  HasNonDeletedCopyOrMove = true;
6695  }
6696 
6697  if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6700  return false;
6701  HasNonDeletedCopyOrMove = true;
6702  }
6703 
6706  return false;
6707 
6708  for (const CXXMethodDecl *MD : D->methods()) {
6709  if (MD->isDeleted())
6710  continue;
6711 
6712  auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6713  if (CD && CD->isCopyOrMoveConstructor())
6714  HasNonDeletedCopyOrMove = true;
6715  else if (!isa<CXXDestructorDecl>(MD))
6716  continue;
6717 
6718  if (!MD->isTrivialForCall())
6719  return false;
6720  }
6721 
6722  return HasNonDeletedCopyOrMove;
6723 }
6724 
6725 /// Report an error regarding overriding, along with any relevant
6726 /// overridden methods.
6727 ///
6728 /// \param DiagID the primary error to report.
6729 /// \param MD the overriding method.
6730 static bool
6731 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6732  llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6733  bool IssuedDiagnostic = false;
6734  for (const CXXMethodDecl *O : MD->overridden_methods()) {
6735  if (Report(O)) {
6736  if (!IssuedDiagnostic) {
6737  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6738  IssuedDiagnostic = true;
6739  }
6740  S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6741  }
6742  }
6743  return IssuedDiagnostic;
6744 }
6745 
6746 /// Perform semantic checks on a class definition that has been
6747 /// completing, introducing implicitly-declared members, checking for
6748 /// abstract types, etc.
6749 ///
6750 /// \param S The scope in which the class was parsed. Null if we didn't just
6751 /// parse a class definition.
6752 /// \param Record The completed class.
6754  if (!Record)
6755  return;
6756 
6757  if (Record->isAbstract() && !Record->isInvalidDecl()) {
6758  AbstractUsageInfo Info(*this, Record);
6759  CheckAbstractClassUsage(Info, Record);
6760  }
6761 
6762  // If this is not an aggregate type and has no user-declared constructor,
6763  // complain about any non-static data members of reference or const scalar
6764  // type, since they will never get initializers.
6765  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6766  !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6767  !Record->isLambda()) {
6768  bool Complained = false;
6769  for (const auto *F : Record->fields()) {
6770  if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6771  continue;
6772 
6773  if (F->getType()->isReferenceType() ||
6774  (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6775  if (!Complained) {
6776  Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6777  << Record->getTagKind() << Record;
6778  Complained = true;
6779  }
6780 
6781  Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6782  << F->getType()->isReferenceType()
6783  << F->getDeclName();
6784  }
6785  }
6786  }
6787 
6788  if (Record->getIdentifier()) {
6789  // C++ [class.mem]p13:
6790  // If T is the name of a class, then each of the following shall have a
6791  // name different from T:
6792  // - every member of every anonymous union that is a member of class T.
6793  //
6794  // C++ [class.mem]p14:
6795  // In addition, if class T has a user-declared constructor (12.1), every
6796  // non-static data member of class T shall have a name different from T.
6797  DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6798  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6799  ++I) {
6800  NamedDecl *D = (*I)->getUnderlyingDecl();
6801  if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6802  Record->hasUserDeclaredConstructor()) ||
6803  isa<IndirectFieldDecl>(D)) {
6804  Diag((*I)->getLocation(), diag::err_member_name_of_class)
6805  << D->getDeclName();
6806  break;
6807  }
6808  }
6809  }
6810 
6811  // Warn if the class has virtual methods but non-virtual public destructor.
6812  if (Record->isPolymorphic() && !Record->isDependentType()) {
6813  CXXDestructorDecl *dtor = Record->getDestructor();
6814  if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6815  !Record->hasAttr<FinalAttr>())
6816  Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6817  diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6818  }
6819 
6820  if (Record->isAbstract()) {
6821  if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6822  Diag(Record->getLocation(), diag::warn_abstract_final_class)
6823  << FA->isSpelledAsSealed();
6824  DiagnoseAbstractType(Record);
6825  }
6826  }
6827 
6828  // Warn if the class has a final destructor but is not itself marked final.
6829  if (!Record->hasAttr<FinalAttr>()) {
6830  if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6831  if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6832  Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6833  << FA->isSpelledAsSealed()
6835  getLocForEndOfToken(Record->getLocation()),
6836  (FA->isSpelledAsSealed() ? " sealed" : " final"));
6837  Diag(Record->getLocation(),
6838  diag::note_final_dtor_non_final_class_silence)
6839  << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6840  }
6841  }
6842  }
6843 
6844  // See if trivial_abi has to be dropped.
6845  if (Record->hasAttr<TrivialABIAttr>())
6847 
6848  // Set HasTrivialSpecialMemberForCall if the record has attribute
6849  // "trivial_abi".
6850  bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6851 
6852  if (HasTrivialABI)
6854 
6855  // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6856  // We check these last because they can depend on the properties of the
6857  // primary comparison functions (==, <=>).
6858  llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6859 
6860  // Perform checks that can't be done until we know all the properties of a
6861  // member function (whether it's defaulted, deleted, virtual, overriding,
6862  // ...).
6863  auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6864  // A static function cannot override anything.
6865  if (MD->getStorageClass() == SC_Static) {
6866  if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6867  [](const CXXMethodDecl *) { return true; }))
6868  return;
6869  }
6870 
6871  // A deleted function cannot override a non-deleted function and vice
6872  // versa.
6873  if (ReportOverrides(*this,
6874  MD->isDeleted() ? diag::err_deleted_override
6875  : diag::err_non_deleted_override,
6876  MD, [&](const CXXMethodDecl *V) {
6877  return MD->isDeleted() != V->isDeleted();
6878  })) {
6879  if (MD->isDefaulted() && MD->isDeleted())
6880  // Explain why this defaulted function was deleted.
6882  return;
6883  }
6884 
6885  // A consteval function cannot override a non-consteval function and vice
6886  // versa.
6887  if (ReportOverrides(*this,
6888  MD->isConsteval() ? diag::err_consteval_override
6889  : diag::err_non_consteval_override,
6890  MD, [&](const CXXMethodDecl *V) {
6891  return MD->isConsteval() != V->isConsteval();
6892  })) {
6893  if (MD->isDefaulted() && MD->isDeleted())
6894  // Explain why this defaulted function was deleted.
6896  return;
6897  }
6898  };
6899 
6900  auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6901  if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6902  return false;
6903 
6907  DefaultedSecondaryComparisons.push_back(FD);
6908  return true;
6909  }
6910 
6912  return false;
6913  };
6914 
6915  auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6916  // Check whether the explicitly-defaulted members are valid.
6917  bool Incomplete = CheckForDefaultedFunction(M);
6918 
6919  // Skip the rest of the checks for a member of a dependent class.
6920  if (Record->isDependentType())
6921  return;
6922 
6923  // For an explicitly defaulted or deleted special member, we defer
6924  // determining triviality until the class is complete. That time is now!
6926  if (!M->isImplicit() && !M->isUserProvided()) {
6927  if (CSM != CXXInvalid) {
6928  M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6929  // Inform the class that we've finished declaring this member.
6931  M->setTrivialForCall(
6932  HasTrivialABI ||
6934  Record->setTrivialForCallFlags(M);
6935  }
6936  }
6937 
6938  // Set triviality for the purpose of calls if this is a user-provided
6939  // copy/move constructor or destructor.
6940  if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6941  CSM == CXXDestructor) && M->isUserProvided()) {
6942  M->setTrivialForCall(HasTrivialABI);
6943  Record->setTrivialForCallFlags(M);
6944  }
6945 
6946  if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6947  M->hasAttr<DLLExportAttr>()) {
6948  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6949  M->isTrivial() &&
6950  (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6951  CSM == CXXDestructor))
6952  M->dropAttr<DLLExportAttr>();
6953 
6954  if (M->hasAttr<DLLExportAttr>()) {
6955  // Define after any fields with in-class initializers have been parsed.
6956  DelayedDllExportMemberFunctions.push_back(M);
6957  }
6958  }
6959 
6960  // Define defaulted constexpr virtual functions that override a base class
6961  // function right away.
6962  // FIXME: We can defer doing this until the vtable is marked as used.
6963  if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6964  DefineDefaultedFunction(*this, M, M->getLocation());
6965 
6966  if (!Incomplete)
6967  CheckCompletedMemberFunction(M);
6968  };
6969 
6970  // Check the destructor before any other member function. We need to
6971  // determine whether it's trivial in order to determine whether the claas
6972  // type is a literal type, which is a prerequisite for determining whether
6973  // other special member functions are valid and whether they're implicitly
6974  // 'constexpr'.
6975  if (CXXDestructorDecl *Dtor = Record->getDestructor())
6976  CompleteMemberFunction(Dtor);
6977 
6978  bool HasMethodWithOverrideControl = false,
6979  HasOverridingMethodWithoutOverrideControl = false;
6980  for (auto *D : Record->decls()) {
6981  if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6982  // FIXME: We could do this check for dependent types with non-dependent
6983  // bases.
6984  if (!Record->isDependentType()) {
6985  // See if a method overloads virtual methods in a base
6986  // class without overriding any.
6987  if (!M->isStatic())
6989  if (M->hasAttr<OverrideAttr>())
6990  HasMethodWithOverrideControl = true;
6991  else if (M->size_overridden_methods() > 0)
6992  HasOverridingMethodWithoutOverrideControl = true;
6993  }
6994 
6995  if (!isa<CXXDestructorDecl>(M))
6996  CompleteMemberFunction(M);
6997  } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6998  CheckForDefaultedFunction(
6999  dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7000  }
7001  }
7002 
7003  if (HasOverridingMethodWithoutOverrideControl) {
7004  bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7005  for (auto *M : Record->methods())
7006  DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7007  }
7008 
7009  // Check the defaulted secondary comparisons after any other member functions.
7010  for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7012 
7013  // If this is a member function, we deferred checking it until now.
7014  if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7015  CheckCompletedMemberFunction(MD);
7016  }
7017 
7018  // ms_struct is a request to use the same ABI rules as MSVC. Check
7019  // whether this class uses any C++ features that are implemented
7020  // completely differently in MSVC, and if so, emit a diagnostic.
7021  // That diagnostic defaults to an error, but we allow projects to
7022  // map it down to a warning (or ignore it). It's a fairly common
7023  // practice among users of the ms_struct pragma to mass-annotate
7024  // headers, sweeping up a bunch of types that the project doesn't
7025  // really rely on MSVC-compatible layout for. We must therefore
7026  // support "ms_struct except for C++ stuff" as a secondary ABI.
7027  // Don't emit this diagnostic if the feature was enabled as a
7028  // language option (as opposed to via a pragma or attribute), as
7029  // the option -mms-bitfields otherwise essentially makes it impossible
7030  // to build C++ code, unless this diagnostic is turned off.
7031  if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7032  (Record->isPolymorphic() || Record->getNumBases())) {
7033  Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7034  }
7035 
7038 
7039  bool ClangABICompat4 =
7040  Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7042  Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7043  bool CanPass = canPassInRegisters(*this, Record, CCK);
7044 
7045  // Do not change ArgPassingRestrictions if it has already been set to
7046  // APK_CanNeverPassInRegs.
7048  Record->setArgPassingRestrictions(CanPass
7051 
7052  // If canPassInRegisters returns true despite the record having a non-trivial
7053  // destructor, the record is destructed in the callee. This happens only when
7054  // the record or one of its subobjects has a field annotated with trivial_abi
7055  // or a field qualified with ObjC __strong/__weak.
7057  Record->setParamDestroyedInCallee(true);
7058  else if (Record->hasNonTrivialDestructor())
7059  Record->setParamDestroyedInCallee(CanPass);
7060 
7061  if (getLangOpts().ForceEmitVTables) {
7062  // If we want to emit all the vtables, we need to mark it as used. This
7063  // is especially required for cases like vtable assumption loads.
7064  MarkVTableUsed(Record->getInnerLocStart(), Record);
7065  }
7066 
7067  if (getLangOpts().CUDA) {
7068  if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7070  else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7072  }
7073 }
7074 
7075 /// Look up the special member function that would be called by a special
7076 /// member function for a subobject of class type.
7077 ///
7078 /// \param Class The class type of the subobject.
7079 /// \param CSM The kind of special member function.
7080 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7081 /// \param ConstRHS True if this is a copy operation with a const object
7082 /// on its RHS, that is, if the argument to the outer special member
7083 /// function is 'const' and this is not a field marked 'mutable'.
7085  Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7086  unsigned FieldQuals, bool ConstRHS) {
7087  unsigned LHSQuals = 0;
7088  if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7089  LHSQuals = FieldQuals;
7090 
7091  unsigned RHSQuals = FieldQuals;
7092  if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7093  RHSQuals = 0;
7094  else if (ConstRHS)
7095  RHSQuals |= Qualifiers::Const;
7096 
7097  return S.LookupSpecialMember(Class, CSM,
7098  RHSQuals & Qualifiers::Const,
7099  RHSQuals & Qualifiers::Volatile,
7100  false,
7101  LHSQuals & Qualifiers::Const,
7102  LHSQuals & Qualifiers::Volatile);
7103 }
7104 
7106  Sema &S;
7107  SourceLocation UseLoc;
7108 
7109  /// A mapping from the base classes through which the constructor was
7110  /// inherited to the using shadow declaration in that base class (or a null
7111  /// pointer if the constructor was declared in that base class).
7112  llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7113  InheritedFromBases;
7114 
7115 public:
7118  : S(S), UseLoc(UseLoc) {
7119  bool DiagnosedMultipleConstructedBases = false;
7120  CXXRecordDecl *ConstructedBase = nullptr;
7121  BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7122 
7123  // Find the set of such base class subobjects and check that there's a
7124  // unique constructed subobject.
7125  for (auto *D : Shadow->redecls()) {
7126  auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7127  auto *DNominatedBase = DShadow->getNominatedBaseClass();
7128  auto *DConstructedBase = DShadow->getConstructedBaseClass();
7129 
7130  InheritedFromBases.insert(
7131  std::make_pair(DNominatedBase->getCanonicalDecl(),
7132  DShadow->getNominatedBaseClassShadowDecl()));
7133  if (DShadow->constructsVirtualBase())
7134  InheritedFromBases.insert(
7135  std::make_pair(DConstructedBase->getCanonicalDecl(),
7136  DShadow->getConstructedBaseClassShadowDecl()));
7137  else
7138  assert(DNominatedBase == DConstructedBase);
7139 
7140  // [class.inhctor.init]p2:
7141  // If the constructor was inherited from multiple base class subobjects
7142  // of type B, the program is ill-formed.
7143  if (!ConstructedBase) {
7144  ConstructedBase = DConstructedBase;
7145  ConstructedBaseIntroducer = D->getIntroducer();
7146  } else if (ConstructedBase != DConstructedBase &&
7147  !Shadow->isInvalidDecl()) {
7148  if (!DiagnosedMultipleConstructedBases) {
7149  S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7150  << Shadow->getTargetDecl();
7151  S.Diag(ConstructedBaseIntroducer->getLocation(),
7152  diag::note_ambiguous_inherited_constructor_using)
7153  << ConstructedBase;
7154  DiagnosedMultipleConstructedBases = true;
7155  }
7156  S.Diag(D->getIntroducer()->getLocation(),
7157  diag::note_ambiguous_inherited_constructor_using)
7158  << DConstructedBase;
7159  }
7160  }
7161 
7162  if (DiagnosedMultipleConstructedBases)
7163  Shadow->setInvalidDecl();
7164  }
7165 
7166  /// Find the constructor to use for inherited construction of a base class,
7167  /// and whether that base class constructor inherits the constructor from a
7168  /// virtual base class (in which case it won't actually invoke it).
7169  std::pair<CXXConstructorDecl *, bool>
7171  auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7172  if (It == InheritedFromBases.end())
7173  return std::make_pair(nullptr, false);
7174 
7175  // This is an intermediary class.
7176  if (It->second)
7177  return std::make_pair(
7178  S.findInheritingConstructor(UseLoc, Ctor, It->second),
7179  It->second->constructsVirtualBase());
7180 
7181  // This is the base class from which the constructor was inherited.
7182  return std::make_pair(Ctor, false);
7183  }
7184 };
7185 
7186 /// Is the special member function which would be selected to perform the
7187 /// specified operation on the specified class type a constexpr constructor?
7188 static bool
7190  Sema::CXXSpecialMember CSM, unsigned Quals,
7191  bool ConstRHS,
7192  CXXConstructorDecl *InheritedCtor = nullptr,
7193  Sema::InheritedConstructorInfo *Inherited = nullptr) {
7194  // If we're inheriting a constructor, see if we need to call it for this base
7195  // class.
7196  if (InheritedCtor) {
7197  assert(CSM == Sema::CXXDefaultConstructor);
7198  auto BaseCtor =
7199  Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7200  if (BaseCtor)
7201  return BaseCtor->isConstexpr();
7202  }
7203 
7204  if (CSM == Sema::CXXDefaultConstructor)
7205  return ClassDecl->hasConstexprDefaultConstructor();
7206  if (CSM == Sema::CXXDestructor)
7207  return ClassDecl->hasConstexprDestructor();
7208 
7210  lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7211  if (!SMOR.getMethod())
7212  // A constructor we wouldn't select can't be "involved in initializing"
7213  // anything.
7214  return true;
7215  return SMOR.getMethod()->isConstexpr();
7216 }
7217 
7218 /// Determine whether the specified special member function would be constexpr
7219 /// if it were implicitly defined.
7221  Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7222  bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7223  Sema::InheritedConstructorInfo *Inherited = nullptr) {
7224  if (!S.getLangOpts().CPlusPlus11)
7225  return false;
7226 
7227  // C++11 [dcl.constexpr]p4:
7228  // In the definition of a constexpr constructor [...]
7229  bool Ctor = true;
7230  switch (CSM) {
7232  if (Inherited)
7233  break;
7234  // Since default constructor lookup is essentially trivial (and cannot
7235  // involve, for instance, template instantiation), we compute whether a
7236  // defaulted default constructor is constexpr directly within CXXRecordDecl.
7237  //
7238  // This is important for performance; we need to know whether the default
7239  // constructor is constexpr to determine whether the type is a literal type.
7240  return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7241 
7244  // For copy or move constructors, we need to perform overload resolution.
7245  break;
7246 
7249  if (!S.getLangOpts().CPlusPlus14)
7250  return false;
7251  // In C++1y, we need to perform overload resolution.
7252  Ctor = false;
7253  break;
7254 
7255  case Sema::CXXDestructor:
7256  return ClassDecl->defaultedDestructorIsConstexpr();
7257 
7258  case Sema::CXXInvalid:
7259  return false;
7260  }
7261 
7262  // -- if the class is a non-empty union, or for each non-empty anonymous
7263  // union member of a non-union class, exactly one non-static data member
7264  // shall be initialized; [DR1359]
7265  //
7266  // If we squint, this is guaranteed, since exactly one non-static data member
7267  // will be initialized (if the constructor isn't deleted), we just don't know
7268  // which one.
7269  if (Ctor && ClassDecl->isUnion())
7270  return CSM == Sema::CXXDefaultConstructor
7271  ? ClassDecl->hasInClassInitializer() ||
7272  !ClassDecl->hasVariantMembers()
7273  : true;
7274 
7275  // -- the class shall not have any virtual base classes;
7276  if (Ctor && ClassDecl->getNumVBases())
7277  return false;
7278 
7279  // C++1y [class.copy]p26:
7280  // -- [the class] is a literal type, and
7281  if (!Ctor && !ClassDecl->isLiteral())
7282  return false;
7283 
7284  // -- every constructor involved in initializing [...] base class
7285  // sub-objects shall be a constexpr constructor;
7286  // -- the assignment operator selected to copy/move each direct base
7287  // class is a constexpr function, and
7288  for (const auto &B : ClassDecl->bases()) {
7289  const RecordType *BaseType = B.getType()->getAs<RecordType>();
7290  if (!BaseType) continue;
7291 
7292  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7293  if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7294  InheritedCtor, Inherited))
7295  return false;
7296  }
7297 
7298  // -- every constructor involved in initializing non-static data members
7299  // [...] shall be a constexpr constructor;
7300  // -- every non-static data member and base class sub-object shall be
7301  // initialized
7302  // -- for each non-static data member of X that is of class type (or array
7303  // thereof), the assignment operator selected to copy/move that member is
7304  // a constexpr function
7305  for (const auto *F : ClassDecl->fields()) {
7306  if (F->isInvalidDecl())
7307  continue;
7308  if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7309  continue;
7310  QualType BaseType = S.Context.getBaseElementType(F->getType());
7311  if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7312  CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7313  if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7314  BaseType.getCVRQualifiers(),
7315  ConstArg && !F->isMutable()))
7316  return false;
7317  } else if (CSM == Sema::CXXDefaultConstructor) {
7318  return false;
7319  }
7320  }
7321 
7322  // All OK, it's constexpr!
7323  return true;
7324 }
7325 
7326 namespace {
7327 /// RAII object to register a defaulted function as having its exception
7328 /// specification computed.
7329 struct ComputingExceptionSpec {
7330  Sema &S;
7331 
7332  ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7333  : S(S) {
7336  Ctx.PointOfInstantiation = Loc;
7337  Ctx.Entity = FD;
7338  S.pushCodeSynthesisContext(Ctx);
7339  }
7340  ~ComputingExceptionSpec() {
7342  }
7343 };
7344 }
7345 
7350 
7353  FunctionDecl *FD,
7355 
7358  auto DFK = S.getDefaultedFunctionKind(FD);
7359  if (DFK.isSpecialMember())
7361  S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7362  if (DFK.isComparison())
7363  return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7364  DFK.asComparison());
7365 
7366  auto *CD = cast<CXXConstructorDecl>(FD);
7367  assert(CD->getInheritedConstructor() &&
7368  "only defaulted functions and inherited constructors have implicit "
7369  "exception specs");
7371  S, Loc, CD->getInheritedConstructor().getShadowDecl());
7373  S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7374 }
7375 
7377  CXXMethodDecl *MD) {
7379 
7380  // Build an exception specification pointing back at this member.
7382  EPI.ExceptionSpec.SourceDecl = MD;
7383 
7384  // Set the calling convention to the default for C++ instance methods.
7385  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7386  S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7387  /*IsCXXMethod=*/true));
7388  return EPI;
7389 }
7390 
7392  const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7393  if (FPT->getExceptionSpecType() != EST_Unevaluated)
7394  return;
7395 
7396  // Evaluate the exception specification.
7397  auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7398  auto ESI = IES.getExceptionSpec();
7399 
7400  // Update the type of the special member to use it.
7401  UpdateExceptionSpec(FD, ESI);
7402 }
7403 
7405  assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7406 
7408  if (!DefKind) {
7409  assert(FD->getDeclContext()->isDependentContext());
7410  return;
7411  }
7412 
7413  if (DefKind.isComparison())
7414  UnusedPrivateFields.clear();
7415 
7416  if (DefKind.isSpecialMember()
7417  ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7418  DefKind.asSpecialMember())
7420  FD->setInvalidDecl();
7421 }
7422 
7424  CXXSpecialMember CSM) {
7425  CXXRecordDecl *RD = MD->getParent();
7426 
7427  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7428  "not an explicitly-defaulted special member");
7429 
7430  // Defer all checking for special members of a dependent type.
7431  if (RD->isDependentType())
7432  return false;
7433 
7434  // Whether this was the first-declared instance of the constructor.
7435  // This affects whether we implicitly add an exception spec and constexpr.
7436  bool First = MD == MD->getCanonicalDecl();
7437 
7438  bool HadError = false;
7439 
7440  // C++11 [dcl.fct.def.default]p1:
7441  // A function that is explicitly defaulted shall
7442  // -- be a special member function [...] (checked elsewhere),
7443  // -- have the same type (except for ref-qualifiers, and except that a
7444  // copy operation can take a non-const reference) as an implicit
7445  // declaration, and
7446  // -- not have default arguments.
7447  // C++2a changes the second bullet to instead delete the function if it's
7448  // defaulted on its first declaration, unless it's "an assignment operator,
7449  // and its return type differs or its parameter type is not a reference".
7450  bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7451  bool ShouldDeleteForTypeMismatch = false;
7452  unsigned ExpectedParams = 1;
7453  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7454  ExpectedParams = 0;
7455  if (MD->getNumParams() != ExpectedParams) {
7456  // This checks for default arguments: a copy or move constructor with a
7457  // default argument is classified as a default constructor, and assignment
7458  // operations and destructors can't have default arguments.
7459  Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7460  << CSM << MD->getSourceRange();
7461  HadError = true;
7462  } else if (MD->isVariadic()) {
7463  if (DeleteOnTypeMismatch)
7464  ShouldDeleteForTypeMismatch = true;
7465  else {
7466  Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7467  << CSM << MD->getSourceRange();
7468  HadError = true;
7469  }
7470  }
7471 
7473 
7474  bool CanHaveConstParam = false;
7475  if (CSM == CXXCopyConstructor)
7476  CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7477  else if (CSM == CXXCopyAssignment)
7478  CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7479 
7480  QualType ReturnType = Context.VoidTy;
7481  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7482  // Check for return type matching.
7483  ReturnType = Type->getReturnType();
7484 
7485  QualType DeclType = Context.getTypeDeclType(RD);
7486  DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7487  QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7488 
7489  if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7490  Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7491  << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7492  HadError = true;
7493  }
7494 
7495  // A defaulted special member cannot have cv-qualifiers.
7496  if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7497  if (DeleteOnTypeMismatch)
7498  ShouldDeleteForTypeMismatch = true;
7499  else {
7500  Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7501  << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7502  HadError = true;
7503  }
7504  }
7505  }
7506 
7507  // Check for parameter type matching.
7508  QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7509  bool HasConstParam = false;
7510  if (ExpectedParams && ArgType->isReferenceType()) {
7511  // Argument must be reference to possibly-const T.
7512  QualType ReferentType = ArgType->getPointeeType();
7513  HasConstParam = ReferentType.isConstQualified();
7514 
7515  if (ReferentType.isVolatileQualified()) {
7516  if (DeleteOnTypeMismatch)
7517  ShouldDeleteForTypeMismatch = true;
7518  else {
7519  Diag(MD->getLocation(),
7520  diag::err_defaulted_special_member_volatile_param) << CSM;
7521  HadError = true;
7522  }
7523  }
7524 
7525  if (HasConstParam && !CanHaveConstParam) {
7526  if (DeleteOnTypeMismatch)
7527  ShouldDeleteForTypeMismatch = true;
7528  else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7529  Diag(MD->getLocation(),
7530  diag::err_defaulted_special_member_copy_const_param)
7531  << (CSM == CXXCopyAssignment);
7532  // FIXME: Explain why this special member can't be const.
7533  HadError = true;
7534  } else {
7535  Diag(MD->getLocation(),
7536  diag::err_defaulted_special_member_move_const_param)
7537  << (CSM == CXXMoveAssignment);
7538  HadError = true;
7539  }
7540  }
7541  } else if (ExpectedParams) {
7542  // A copy assignment operator can take its argument by value, but a
7543  // defaulted one cannot.
7544  assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7545  Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7546  HadError = true;
7547  }
7548 
7549  // C++11 [dcl.fct.def.default]p2:
7550  // An explicitly-defaulted function may be declared constexpr only if it
7551  // would have been implicitly declared as constexpr,
7552  // Do not apply this rule to members of class templates, since core issue 1358
7553  // makes such functions always instantiate to constexpr functions. For
7554  // functions which cannot be constexpr (for non-constructors in C++11 and for
7555  // destructors in C++14 and C++17), this is checked elsewhere.
7556  //
7557  // FIXME: This should not apply if the member is deleted.
7558  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7559  HasConstParam);
7560  if ((getLangOpts().CPlusPlus20 ||
7561  (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7562  : isa<CXXConstructorDecl>(MD))) &&
7563  MD->isConstexpr() && !Constexpr &&
7565  Diag(MD->getBeginLoc(), MD->isConsteval()
7566  ? diag::err_incorrect_defaulted_consteval
7567  : diag::err_incorrect_defaulted_constexpr)
7568  << CSM;
7569  // FIXME: Explain why the special member can't be constexpr.
7570  HadError = true;
7571  }
7572 
7573  if (First) {
7574  // C++2a [dcl.fct.def.default]p3:
7575  // If a function is explicitly defaulted on its first declaration, it is
7576  // implicitly considered to be constexpr if the implicit declaration
7577  // would be.
7582 
7583  if (!Type->hasExceptionSpec()) {
7584  // C++2a [except.spec]p3:
7585  // If a declaration of a function does not have a noexcept-specifier
7586  // [and] is defaulted on its first declaration, [...] the exception
7587  // specification is as specified below
7588  FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7590  EPI.ExceptionSpec.SourceDecl = MD;
7591  MD->setType(Context.getFunctionType(ReturnType,
7592  llvm::makeArrayRef(&ArgType,
7593  ExpectedParams),
7594  EPI));
7595  }
7596  }
7597 
7598  if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7599  if (First) {
7600  SetDeclDeleted(MD, MD->getLocation());
7601  if (!inTemplateInstantiation() && !HadError) {
7602  Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7603  if (ShouldDeleteForTypeMismatch) {
7604  Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7605  } else {
7606  ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7607  }
7608  }
7609  if (ShouldDeleteForTypeMismatch && !HadError) {
7610  Diag(MD->getLocation(),
7611  diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7612  }
7613  } else {
7614  // C++11 [dcl.fct.def.default]p4:
7615  // [For a] user-provided explicitly-defaulted function [...] if such a
7616  // function is implicitly defined as deleted, the program is ill-formed.
7617  Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7618  assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7619  ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7620  HadError = true;
7621  }
7622  }
7623 
7624  return HadError;
7625 }
7626 
7627 namespace {
7628 /// Helper class for building and checking a defaulted comparison.
7629 ///
7630 /// Defaulted functions are built in two phases:
7631 ///
7632 /// * First, the set of operations that the function will perform are
7633 /// identified, and some of them are checked. If any of the checked
7634 /// operations is invalid in certain ways, the comparison function is
7635 /// defined as deleted and no body is built.
7636 /// * Then, if the function is not defined as deleted, the body is built.
7637 ///
7638 /// This is accomplished by performing two visitation steps over the eventual
7639 /// body of the function.
7640 template<typename Derived, typename ResultList, typename Result,
7641  typename Subobject>
7642 class DefaultedComparisonVisitor {
7643 public:
7645 
7646  DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7648  : S(S), RD(RD), FD(FD), DCK(DCK) {
7649  if (auto *Info = FD->getDefaultedFunctionInfo()) {
7650  // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7651  // UnresolvedSet to avoid this copy.
7652  Fns.assign(Info->getUnqualifiedLookups().begin(),
7653  Info->getUnqualifiedLookups().end());
7654  }
7655  }
7656 
7657  ResultList visit() {
7658  // The type of an lvalue naming a parameter of this function.
7659  QualType ParamLvalType =
7661 
7662  ResultList Results;
7663 
7664  switch (DCK) {
7666  llvm_unreachable("not a defaulted comparison");
7667 
7670  getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7671  return Results;
7672 
7675  Results.add(getDerived().visitExpandedSubobject(
7676  ParamLvalType, getDerived().getCompleteObject()));
7677  return Results;
7678  }
7679  llvm_unreachable("");
7680  }
7681 
7682 protected:
7683  Derived &getDerived() { return static_cast<Derived&>(*this); }
7684 
7685  /// Visit the expanded list of subobjects of the given type, as specified in
7686  /// C++2a [class.compare.default].
7687  ///
7688  /// \return \c true if the ResultList object said we're done, \c false if not.
7689  bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7690  Qualifiers Quals) {
7691  // C++2a [class.compare.default]p4:
7692  // The direct base class subobjects of C
7693  for (CXXBaseSpecifier &Base : Record->bases())
7694  if (Results.add(getDerived().visitSubobject(
7695  S.Context.getQualifiedType(Base.getType(), Quals),
7696  getDerived().getBase(&Base))))
7697  return true;
7698 
7699  // followed by the non-static data members of C
7700  for (FieldDecl *Field : Record->fields()) {
7701  // Recursively expand anonymous structs.
7702  if (Field->isAnonymousStructOrUnion()) {
7703  if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7704  Quals))
7705  return true;
7706  continue;
7707  }
7708 
7709  // Figure out the type of an lvalue denoting this field.
7710  Qualifiers FieldQuals = Quals;
7711  if (Field->isMutable())
7712  FieldQuals.removeConst();
7713  QualType FieldType =
7714  S.Context.getQualifiedType(Field->getType(), FieldQuals);
7715 
7716  if (Results.add(getDerived().visitSubobject(
7717  FieldType, getDerived().getField(Field))))
7718  return true;
7719  }
7720 
7721  // form a list of subobjects.
7722  return false;
7723  }
7724 
7725  Result visitSubobject(QualType Type, Subobject Subobj) {
7726  // In that list, any subobject of array type is recursively expanded
7727  const ArrayType *AT = S.Context.getAsArrayType(Type);
7728  if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7729  return getDerived().visitSubobjectArray(CAT->getElementType(),
7730  CAT->getSize(), Subobj);
7731  return getDerived().visitExpandedSubobject(Type, Subobj);
7732  }
7733 
7734  Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7735  Subobject Subobj) {
7736  return getDerived().visitSubobject(Type, Subobj);
7737  }
7738 
7739 protected:
7740  Sema &S;
7741  CXXRecordDecl *RD;
7742  FunctionDecl *FD;
7744  UnresolvedSet<16> Fns;
7745 };
7746 
7747 /// Information about a defaulted comparison, as determined by
7748 /// DefaultedComparisonAnalyzer.
7749 struct DefaultedComparisonInfo {
7750  bool Deleted = false;
7751  bool Constexpr = true;
7753 
7754  static DefaultedComparisonInfo deleted() {
7755  DefaultedComparisonInfo Deleted;
7756  Deleted.Deleted = true;
7757  return Deleted;
7758  }
7759 
7760  bool add(const DefaultedComparisonInfo &R) {
7761  Deleted |= R.Deleted;
7762  Constexpr &= R.Constexpr;
7763  Category = commonComparisonType(Category, R.Category);
7764  return Deleted;
7765  }
7766 };
7767 
7768 /// An element in the expanded list of subobjects of a defaulted comparison, as
7769 /// specified in C++2a [class.compare.default]p4.
7770 struct DefaultedComparisonSubobject {
7771  enum { CompleteObject, Member, Base } Kind;
7772  NamedDecl *Decl;
7773  SourceLocation Loc;
7774 };
7775 
7776 /// A visitor over the notional body of a defaulted comparison that determines
7777 /// whether that body would be deleted or constexpr.
7778 class DefaultedComparisonAnalyzer
7779  : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7780  DefaultedComparisonInfo,
7781  DefaultedComparisonInfo,
7782  DefaultedComparisonSubobject> {
7783 public:
7784  enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7785 
7786 private:
7787  DiagnosticKind Diagnose;
7788 
7789 public:
7790  using Base = DefaultedComparisonVisitor;
7791  using Result = DefaultedComparisonInfo;
7792  using Subobject = DefaultedComparisonSubobject;
7793 
7794  friend Base;
7795 
7796  DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7798  DiagnosticKind Diagnose = NoDiagnostics)
7799  : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7800 
7801  Result visit() {
7802  if ((DCK == DefaultedComparisonKind::Equal ||
7804  RD->hasVariantMembers()) {
7805  // C++2a [class.compare.default]p2 [P2002R0]:
7806  // A defaulted comparison operator function for class C is defined as
7807  // deleted if [...] C has variant members.
7808  if (Diagnose == ExplainDeleted) {
7809  S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7810  << FD << RD->isUnion() << RD;
7811  }
7812  return Result::deleted();
7813  }
7814 
7815  return Base::visit();
7816  }
7817 
7818 private:
7819  Subobject getCompleteObject() {
7820  return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7821  }
7822 
7823  Subobject getBase(CXXBaseSpecifier *Base) {
7824  return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7825  Base->getBaseTypeLoc()};
7826  }
7827 
7828  Subobject getField(FieldDecl *Field) {
7829  return Subobject{Subobject::Member, Field, Field->getLocation()};
7830  }
7831 
7832  Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7833  // C++2a [class.compare.default]p2 [P2002R0]:
7834  // A defaulted <=> or == operator function for class C is defined as
7835  // deleted if any non-static data member of C is of reference type
7836  if (Type->isReferenceType()) {
7837  if (Diagnose == ExplainDeleted) {
7838  S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7839  << FD << RD;
7840  }
7841  return Result::deleted();
7842  }
7843 
7844  // [...] Let xi be an lvalue denoting the ith element [...]
7846  Expr *Args[] = {&Xi, &Xi};
7847 
7848  // All operators start by trying to apply that same operator recursively.
7850  assert(OO != OO_None && "not an overloaded operator!");
7851  return visitBinaryOperator(OO, Args, Subobj);
7852  }
7853 
7854  Result
7855  visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7856  Subobject Subobj,
7857  OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7858  // Note that there is no need to consider rewritten candidates here if
7859  // we've already found there is no viable 'operator<=>' candidate (and are
7860  // considering synthesizing a '<=>' from '==' and '<').
7861  OverloadCandidateSet CandidateSet(
7864  OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7865 
7866  /// C++2a [class.compare.default]p1 [P2002R0]:
7867  /// [...] the defaulted function itself is never a candidate for overload
7868  /// resolution [...]
7869  CandidateSet.exclude(FD);
7870 
7871  if (Args[0]->getType()->isOverloadableType())
7872  S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7873  else
7874  // FIXME: We determine whether this is a valid expression by checking to
7875  // see if there's a viable builtin operator candidate for it. That isn't
7876  // really what the rules ask us to do, but should give the right results.
7877  S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7878 
7879  Result R;
7880 
7882  switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7883  case OR_Success: {
7884  // C++2a [class.compare.secondary]p2 [P2002R0]:
7885  // The operator function [...] is defined as deleted if [...] the
7886  // candidate selected by overload resolution is not a rewritten
7887  // candidate.
7888  if ((DCK == DefaultedComparisonKind::NotEqual ||
7890  !Best->RewriteKind) {
7891  if (Diagnose == ExplainDeleted) {
7892  if (Best->Function) {
7893  S.Diag(Best->Function->getLocation(),
7894  diag::note_defaulted_comparison_not_rewritten_callee)
7895  << FD;
7896  } else {
7897  assert(Best->Conversions.size() == 2 &&
7898  Best->Conversions[0].isUserDefined() &&
7899  "non-user-defined conversion from class to built-in "
7900  "comparison");
7901  S.Diag(Best->Conversions[0]
7902  .UserDefined.FoundConversionFunction.getDecl()
7903  ->getLocation(),
7904  diag::note_defaulted_comparison_not_rewritten_conversion)
7905  << FD;
7906  }
7907  }
7908  return Result::deleted();
7909  }
7910 
7911  // Throughout C++2a [class.compare]: if overload resolution does not
7912  // result in a usable function, the candidate function is defined as
7913  // deleted. This requires that we selected an accessible function.
7914  //
7915  // Note that this only considers the access of the function when named
7916  // within the type of the subobject, and not the access path for any
7917  // derived-to-base conversion.
7918  CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7919  if (ArgClass && Best->FoundDecl.getDecl() &&
7920  Best->FoundDecl.getDecl()->isCXXClassMember()) {
7921  QualType ObjectType = Subobj.Kind == Subobject::Member
7922  ? Args[0]->getType()
7923  : S.Context.getRecordType(RD);
7925  ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7926  Diagnose == ExplainDeleted
7927  ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7928  << FD << Subobj.Kind << Subobj.Decl
7929  : S.PDiag()))
7930  return Result::deleted();
7931  }
7932 
7933  bool NeedsDeducing =
7934  OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7935 
7936  if (FunctionDecl *BestFD = Best->Function) {
7937  // C++2a [class.compare.default]p3 [P2002R0]:
7938  // A defaulted comparison function is constexpr-compatible if
7939  // [...] no overlod resolution performed [...] results in a
7940  // non-constexpr function.
7941  assert(!BestFD->isDeleted() && "wrong overload resolution result");
7942  // If it's not constexpr, explain why not.
7943  if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7944  if (Subobj.Kind != Subobject::CompleteObject)
7945  S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7946  << Subobj.Kind << Subobj.Decl;
7947  S.Diag(BestFD->getLocation(),
7948  diag::note_defaulted_comparison_not_constexpr_here);
7949  // Bail out after explaining; we don't want any more notes.
7950  return Result::deleted();
7951  }
7952  R.Constexpr &= BestFD->isConstexpr();
7953 
7954  if (NeedsDeducing) {
7955  // If any callee has an undeduced return type, deduce it now.
7956  // FIXME: It's not clear how a failure here should be handled. For
7957  // now, we produce an eager diagnostic, because that is forward
7958  // compatible with most (all?) other reasonable options.
7959  if (BestFD->getReturnType()->isUndeducedType() &&
7960  S.DeduceReturnType(BestFD, FD->getLocation(),
7961  /*Diagnose=*/false)) {
7962  // Don't produce a duplicate error when asked to explain why the
7963  // comparison is deleted: we diagnosed that when initially checking
7964  // the defaulted operator.
7965  if (Diagnose == NoDiagnostics) {
7966  S.Diag(
7967  FD->getLocation(),
7968  diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7969  << Subobj.Kind << Subobj.Decl;
7970  S.Diag(
7971  Subobj.Loc,
7972  diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7973  << Subobj.Kind << Subobj.Decl;
7974  S.Diag(BestFD->getLocation(),
7975  diag::note_defaulted_comparison_cannot_deduce_callee)
7976  << Subobj.Kind << Subobj.Decl;
7977  }
7978  return Result::deleted();
7979  }
7980  auto *Info = S.Context.CompCategories.lookupInfoForType(
7981  BestFD->getCallResultType());
7982  if (!Info) {
7983  if (Diagnose == ExplainDeleted) {
7984  S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7985  << Subobj.Kind << Subobj.Decl
7986  << BestFD->getCallResultType().withoutLocalFastQualifiers();
7987  S.Diag(BestFD->getLocation(),
7988  diag::note_defaulted_comparison_cannot_deduce_callee)
7989  << Subobj.Kind << Subobj.Decl;
7990  }
7991  return Result::deleted();
7992  }
7993  R.Category = Info->Kind;
7994  }
7995  } else {
7996  QualType T = Best->BuiltinParamTypes[0];
7997  assert(T == Best->BuiltinParamTypes[1] &&
7998  "builtin comparison for different types?");
7999  assert(Best->BuiltinParamTypes[2].isNull() &&
8000  "invalid builtin comparison");
8001 
8002  if (NeedsDeducing) {
8005  assert(Cat && "no category for builtin comparison?");
8006  R.Category = *Cat;
8007  }
8008  }
8009 
8010  // Note that we might be rewriting to a different operator. That call is
8011  // not considered until we come to actually build the comparison function.
8012  break;
8013  }
8014 
8015  case OR_Ambiguous:
8016  if (Diagnose == ExplainDeleted) {
8017  unsigned Kind = 0;
8018  if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8019  Kind = OO == OO_EqualEqual ? 1 : 2;
8020  CandidateSet.NoteCandidates(
8022  Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8023  << FD << Kind << Subobj.Kind << Subobj.Decl),
8024  S, OCD_AmbiguousCandidates, Args);
8025  }
8026  R = Result::deleted();
8027  break;
8028 
8029  case OR_Deleted:
8030  if (Diagnose == ExplainDeleted) {
8031  if ((DCK == DefaultedComparisonKind::NotEqual ||
8033  !Best->RewriteKind) {
8034  S.Diag(Best->Function->getLocation(),
8035  diag::note_defaulted_comparison_not_rewritten_callee)
8036  << FD;
8037  } else {
8038  S.Diag(Subobj.Loc,
8039  diag::note_defaulted_comparison_calls_deleted)
8040  << FD << Subobj.Kind << Subobj.Decl;
8041  S.NoteDeletedFunction(Best->Function);
8042  }
8043  }
8044  R = Result::deleted();
8045  break;
8046 
8047  case OR_No_Viable_Function:
8048  // If there's no usable candidate, we're done unless we can rewrite a
8049  // '<=>' in terms of '==' and '<'.
8050  if (OO == OO_Spaceship &&
8052  // For any kind of comparison category return type, we need a usable
8053  // '==' and a usable '<'.
8054  if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8055  &CandidateSet)))
8056  R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8057  break;
8058  }
8059 
8060  if (Diagnose == ExplainDeleted) {
8061  S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8062  << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8063 
8064  // For a three-way comparison, list both the candidates for the
8065  // original operator and the candidates for the synthesized operator.
8066  if (SpaceshipCandidates) {
8067  SpaceshipCandidates->NoteCandidates(
8068  S, Args,
8069  SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8070  Args, FD->getLocation()));
8071  S.Diag(Subobj.Loc,
8072  diag::note_defaulted_comparison_no_viable_function_synthesized)
8073  << (OO == OO_EqualEqual ? 0 : 1);
8074  }
8075 
8076  CandidateSet.NoteCandidates(
8077  S, Args,
8078  CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8079  FD->getLocation()));
8080  }
8081  R = Result::deleted();
8082  break;
8083  }
8084 
8085  return R;
8086  }
8087 };
8088 
8089 /// A list of statements.
8090 struct StmtListResult {
8091  bool IsInvalid = false;
8093 
8094  bool add(const StmtResult &S) {
8095  IsInvalid |= S.isInvalid();
8096  if (IsInvalid)
8097  return true;
8098  Stmts.push_back(S.get());
8099  return false;
8100  }
8101 };
8102 
8103 /// A visitor over the notional body of a defaulted comparison that synthesizes
8104 /// the actual body.
8105 class DefaultedComparisonSynthesizer
8106  : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8107  StmtListResult, StmtResult,
8108  std::pair<ExprResult, ExprResult>> {
8109  SourceLocation Loc;
8110  unsigned ArrayDepth = 0;
8111 
8112 public:
8113  using Base = DefaultedComparisonVisitor;
8114  using ExprPair = std::pair<ExprResult, ExprResult>;
8115 
8116  friend Base;
8117 
8118  DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8120  SourceLocation BodyLoc)
8121  : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8122 
8123  /// Build a suitable function body for this defaulted comparison operator.
8124  StmtResult build() {
8125  Sema::CompoundScopeRAII CompoundScope(S);
8126 
8127  StmtListResult Stmts = visit();
8128  if (Stmts.IsInvalid)
8129  return StmtError();
8130 
8131  ExprResult RetVal;
8132  switch (DCK) {
8134  llvm_unreachable("not a defaulted comparison");
8135 
8137  // C++2a [class.eq]p3:
8138  // [...] compar[e] the corresponding elements [...] until the first
8139  // index i where xi == yi yields [...] false. If no such index exists,
8140  // V is true. Otherwise, V is false.
8141  //
8142  // Join the comparisons with '&&'s and return the result. Use a right
8143  // fold (traversing the conditions right-to-left), because that
8144  // short-circuits more naturally.
8145  auto OldStmts = std::move(Stmts.Stmts);
8146  Stmts.Stmts.clear();
8147  ExprResult CmpSoFar;
8148  // Finish a particular comparison chain.
8149  auto FinishCmp = [&] {
8150  if (Expr *Prior = CmpSoFar.get()) {
8151  // Convert the last expression to 'return ...;'
8152  if (RetVal.isUnset() && Stmts.Stmts.empty())
8153  RetVal = CmpSoFar;
8154  // Convert any prior comparison to 'if (!(...)) return false;'
8155  else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8156  return true;
8157  CmpSoFar = ExprResult();
8158  }
8159  return false;
8160  };
8161  for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8162  Expr *E = dyn_cast<Expr>(EAsStmt);
8163  if (!E) {
8164  // Found an array comparison.
8165  if (FinishCmp() || Stmts.add(EAsStmt))
8166  return StmtError();
8167  continue;
8168  }
8169 
8170  if (CmpSoFar.isUnset()) {
8171  CmpSoFar = E;
8172  continue;
8173  }
8174  CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8175  if (CmpSoFar.isInvalid())
8176  return StmtError();
8177  }
8178  if (FinishCmp())
8179  return StmtError();
8180  std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8181  // If no such index exists, V is true.
8182  if (RetVal.isUnset())
8183  RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8184  break;
8185  }
8186 
8188  // Per C++2a [class.spaceship]p3, as a fallback add:
8189  // return static_cast<R>(std::strong_ordering::equal);
8193  if (StrongOrdering.isNull())
8194  return StmtError();
8195  VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8197  ->VD;
8198  RetVal = getDecl(EqualVD);
8199  if (RetVal.isInvalid())
8200  return StmtError();
8201  RetVal = buildStaticCastToR(RetVal.get());
8202  break;
8203  }
8204 
8207  RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8208  break;
8209  }
8210 
8211  // Build the final return statement.
8212  if (RetVal.isInvalid())
8213  return StmtError();
8214  StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8215  if (ReturnStmt.isInvalid())
8216  return StmtError();
8217  Stmts.Stmts.push_back(ReturnStmt.get());
8218 
8219  return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8220  }
8221 
8222 private:
8223  ExprResult getDecl(ValueDecl *VD) {
8224  return S.BuildDeclarationNameExpr(
8225  CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8226  }
8227 
8228  ExprResult getParam(unsigned I) {
8229  ParmVarDecl *PD = FD->getParamDecl(I);
8230  return getDecl(PD);
8231  }
8232 
8233  ExprPair getCompleteObject() {
8234  unsigned Param = 0;
8235  ExprResult LHS;
8236  if (isa<CXXMethodDecl>(FD)) {
8237  // LHS is '*this'.
8238  LHS = S.ActOnCXXThis(Loc);
8239  if (!LHS.isInvalid())
8240  LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8241  } else {
8242  LHS = getParam(Param++);
8243  }
8244  ExprResult RHS = getParam(Param++);
8245  assert(Param == FD->getNumParams());
8246  return {LHS, RHS};
8247  }
8248 
8249  ExprPair getBase(CXXBaseSpecifier *Base) {
8250  ExprPair Obj = getCompleteObject();
8251  if (Obj.first.isInvalid() || Obj.second.isInvalid())
8252  return {ExprError(), ExprError()};
8253  CXXCastPath Path = {Base};
8254  return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8255  CK_DerivedToBase, VK_LValue, &Path),
8256  S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8257  CK_DerivedToBase, VK_LValue, &Path)};
8258  }
8259 
8260  ExprPair getField(FieldDecl *Field) {
8261  ExprPair Obj = getCompleteObject();
8262  if (Obj.first.isInvalid() || Obj.second.isInvalid())
8263  return {ExprError(), ExprError()};
8264 
8265  DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8266  DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8267  return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8268  CXXScopeSpec(), Field, Found, NameInfo),
8269  S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8270  CXXScopeSpec(), Field, Found, NameInfo)};
8271  }
8272 
8273  // FIXME: When expanding a subobject, register a note in the code synthesis
8274  // stack to say which subobject we're comparing.
8275 
8276  StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8277  if (Cond.isInvalid())
8278  return StmtError();
8279 
8280  ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8281  if (NotCond.isInvalid())
8282  return StmtError();
8283 
8284  ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8285  assert(!False.isInvalid() && "should never fail");
8286  StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8287  if (ReturnFalse.isInvalid())
8288  return StmtError();
8289 
8290  return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8291  S.ActOnCondition(nullptr, Loc, NotCond.get(),
8293  Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8294  }
8295 
8296  StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8297  ExprPair Subobj) {
8298  QualType SizeType = S.Context.getSizeType();
8299  Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8300 
8301  // Build 'size_t i$n = 0'.
8302  IdentifierInfo *IterationVarName = nullptr;
8303  {
8304  SmallString<8> Str;
8305  llvm::raw_svector_ostream OS(Str);
8306  OS << "i" << ArrayDepth;
8307  IterationVarName = &S.Context.Idents.get(OS.str());
8308  }
8309  VarDecl *IterationVar = VarDecl::Create(
8310  S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8311  S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8312  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8313  IterationVar->setInit(
8314  IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8315  Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8316 
8317  auto IterRef = [&] {
8319  CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8320  IterationVar);
8321  assert(!Ref.isInvalid() && "can't reference our own variable?");
8322  return Ref.get();
8323  };
8324 
8325  // Build 'i$n != Size'.
8326  ExprResult Cond = S.CreateBuiltinBinOp(
8327  Loc, BO_NE, IterRef(),
8328  IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8329  assert(!Cond.isInvalid() && "should never fail");
8330 
8331  // Build '++i$n'.
8332  ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8333  assert(!Inc.isInvalid() && "should never fail");
8334 
8335  // Build 'a[i$n]' and 'b[i$n]'.
8336  auto Index = [&](ExprResult E) {
8337  if (E.isInvalid())
8338  return ExprError();
8339  return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8340  };
8341  Subobj.first = Index(Subobj.first);
8342  Subobj.second = Index(Subobj.second);
8343 
8344  // Compare the array elements.
8345  ++ArrayDepth;
8346  StmtResult Substmt = visitSubobject(Type, Subobj);
8347  --ArrayDepth;
8348 
8349  if (Substmt.isInvalid())
8350  return StmtError();
8351 
8352  // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8353  // For outer levels or for an 'operator<=>' we already have a suitable
8354  // statement that returns as necessary.
8355  if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8356  assert(DCK == DefaultedComparisonKind::Equal &&
8357  "should have non-expression statement");
8358  Substmt = buildIfNotCondReturnFalse(ElemCmp);
8359  if (Substmt.isInvalid())
8360  return StmtError();
8361  }
8362 
8363  // Build 'for (...) ...'
8364  return S.ActOnForStmt(Loc, Loc, Init,
8365  S.ActOnCondition(nullptr, Loc, Cond.get(),
8367  S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8368  Substmt.get());
8369  }
8370 
8371  StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8372  if (Obj.first.isInvalid() || Obj.second.isInvalid())
8373  return StmtError();
8374 
8377  ExprResult Op;
8378  if (Type->isOverloadableType())
8379  Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8380  Obj.second.get(), /*PerformADL=*/true,
8381  /*AllowRewrittenCandidates=*/true, FD);
8382  else
8383  Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8384  if (Op.isInvalid())
8385  return StmtError();
8386 
8387  switch (DCK) {
8389  llvm_unreachable("not a defaulted comparison");
8390 
8392  // Per C++2a [class.eq]p2, each comparison is individually contextually
8393  // converted to bool.
8395  if (Op.isInvalid())
8396  return StmtError();
8397  return Op.get();
8398 
8400  // Per C++2a [class.spaceship]p3, form:
8401  // if (R cmp = static_cast<R>(op); cmp != 0)
8402  // return cmp;
8403  QualType R = FD->getReturnType();
8404  Op = buildStaticCastToR(Op.get());
8405  if (Op.isInvalid())
8406  return StmtError();
8407 
8408  // R cmp = ...;
8409  IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8410  VarDecl *VD =
8411  VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8413  S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8414  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8415 
8416  // cmp != 0
8417  ExprResult VDRef = getDecl(VD);
8418  if (VDRef.isInvalid())
8419  return StmtError();
8420  llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8421  Expr *Zero =
8422  IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8423  ExprResult Comp;
8424  if (VDRef.get()->getType()->isOverloadableType())
8425  Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8426  true, FD);
8427  else
8428  Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8429  if (Comp.isInvalid())
8430  return StmtError();
8432  nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8433  if (Cond.isInvalid())
8434  return StmtError();
8435 
8436  // return cmp;
8437  VDRef = getDecl(VD);
8438  if (VDRef.isInvalid())
8439  return StmtError();
8440  StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8441  if (ReturnStmt.isInvalid())
8442  return StmtError();
8443 
8444  // if (...)
8445  return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8446  Loc, ReturnStmt.get(),
8447  /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8448  }
8449 
8452  // C++2a [class.compare.secondary]p2:
8453  // Otherwise, the operator function yields x @ y.
8454  return Op.get();
8455  }
8456  llvm_unreachable("");
8457  }
8458 
8459  /// Build "static_cast<R>(E)".
8460  ExprResult buildStaticCastToR(Expr *E) {
8461  QualType R = FD->getReturnType();
8462  assert(!R->isUndeducedType() && "type should have been deduced already");
8463 
8464  // Don't bother forming a no-op cast in the common case.
8465  if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8466  return E;
8467  return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8468  S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8469  SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8470  }
8471 };
8472 }
8473 
8474 /// Perform the unqualified lookups that might be needed to form a defaulted
8475 /// comparison function for the given operator.
8477  UnresolvedSetImpl &Operators,
8479  auto Lookup = [&](OverloadedOperatorKind OO) {
8480  Self.LookupOverloadedOperatorName(OO, S, Operators);
8481  };
8482 
8483  // Every defaulted operator looks up itself.
8484  Lookup(Op);
8485  // ... and the rewritten form of itself, if any.
8487  Lookup(ExtraOp);
8488 
8489  // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8490  // synthesize a three-way comparison from '<' and '=='. In a dependent
8491  // context, we also need to look up '==' in case we implicitly declare a
8492  // defaulted 'operator=='.
8493  if (Op == OO_Spaceship) {
8494  Lookup(OO_ExclaimEqual);
8495  Lookup(OO_Less);
8496  Lookup(OO_EqualEqual);
8497  }
8498 }
8499 
8502  assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8503 
8504  // Perform any unqualified lookups we're going to need to default this
8505  // function.
8506  if (S) {
8507  UnresolvedSet<32> Operators;
8508  lookupOperatorsForDefaultedComparison(*this, S, Operators,
8509  FD->getOverloadedOperator());
8511  Context, Operators.pairs()));
8512  }
8513 
8514  // C++2a [class.compare.default]p1:
8515  // A defaulted comparison operator function for some class C shall be a
8516  // non-template function declared in the member-specification of C that is
8517  // -- a non-static const member of C having one parameter of type
8518  // const C&, or
8519  // -- a friend of C having two parameters of type const C& or two
8520  // parameters of type C.
8521 
8522  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8523  bool IsMethod = isa<CXXMethodDecl>(FD);
8524  if (IsMethod) {
8525  auto *MD = cast<CXXMethodDecl>(FD);
8526  assert(!MD->isStatic() && "comparison function cannot be a static member");
8527 
8528  // If we're out-of-class, this is the class we're comparing.
8529  if (!RD)
8530  RD = MD->getParent();
8531 
8532  if (!MD->isConst()) {
8533  SourceLocation InsertLoc;
8534  if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8535  InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8536  // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8537  // corresponding defaulted 'operator<=>' already.
8538  if (!MD->isImplicit()) {
8539  Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8540  << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8541  }
8542 
8543  // Add the 'const' to the type to recover.
8544  const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8545  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8546  EPI.TypeQuals.addConst();
8547  MD->setType(Context.getFunctionType(FPT->getReturnType(),
8548  FPT->getParamTypes(), EPI));
8549  }
8550  }
8551 
8552  if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8553  // Let's not worry about using a variadic template pack here -- who would do
8554  // such a thing?
8555  Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8556  << int(IsMethod) << int(DCK);
8557  return true;
8558  }
8559 
8560  const ParmVarDecl *KnownParm = nullptr;
8561  for (const ParmVarDecl *Param : FD->parameters()) {
8562  QualType ParmTy = Param->getType();
8563  if (ParmTy->isDependentType())
8564  continue;
8565  if (!KnownParm) {
8566  auto CTy = ParmTy;
8567  // Is it `T const &`?
8568  bool Ok = !IsMethod;
8569  QualType ExpectedTy;
8570  if (RD)
8571  ExpectedTy = Context.getRecordType(RD);
8572  if (auto *Ref = CTy->getAs<ReferenceType>()) {
8573  CTy = Ref->getPointeeType();
8574  if (RD)
8575  ExpectedTy.addConst();
8576  Ok = true;
8577  }
8578 
8579  // Is T a class?
8580  if (!Ok) {
8581  } else if (RD) {
8582  if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8583  Ok = false;
8584  } else if (auto *CRD = CTy->getAsRecordDecl()) {
8585  RD = cast<CXXRecordDecl>(CRD);
8586  } else {
8587  Ok = false;
8588  }
8589 
8590  if (Ok) {
8591  KnownParm = Param;
8592  } else {
8593  // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8594  // corresponding defaulted 'operator<=>' already.
8595  if (!FD->isImplicit()) {
8596  if (RD) {
8597  QualType PlainTy = Context.getRecordType(RD);
8598  QualType RefTy =
8600  Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8601  << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8602  << Param->getSourceRange();
8603  } else {
8604  assert(!IsMethod && "should know expected type for method");
8605  Diag(FD->getLocation(),
8606  diag::err_defaulted_comparison_param_unknown)
8607  << int(DCK) << ParmTy << Param->getSourceRange();
8608  }
8609  }
8610  return true;
8611  }
8612  } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8613  Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8614  << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8615  << ParmTy << Param->getSourceRange();
8616  return true;
8617  }
8618  }
8619 
8620  assert(RD && "must have determined class");
8621  if (IsMethod) {
8622  } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8623  // In-class, must be a friend decl.
8624  assert(FD->getFriendObjectKind() && "expected a friend declaration");
8625  } else {
8626  // Out of class, require the defaulted comparison to be a friend (of a
8627  // complete type).
8629  diag::err_defaulted_comparison_not_friend, int(DCK),
8630  int(1)))
8631  return true;
8632 
8633  if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
8634  return FD->getCanonicalDecl() ==
8635  F->getFriendDecl()->getCanonicalDecl();
8636  }) == RD->friends().end()) {
8637  Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8638  << int(DCK) << int(0) << RD;
8639  Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8640  return true;
8641  }
8642  }
8643 
8644  // C++2a [class.eq]p1, [class.rel]p1:
8645  // A [defaulted comparison other than <=>] shall have a declared return
8646  // type bool.
8647  if (DCK != DefaultedComparisonKind::ThreeWay &&
8650  Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8651  << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8652  << FD->getReturnTypeSourceRange();
8653  return true;
8654  }
8655  // C++2a [class.spaceship]p2 [P2002R0]:
8656  // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8657  // R shall not contain a placeholder type.
8658  if (DCK == DefaultedComparisonKind::ThreeWay &&
8662  Diag(FD->getLocation(),
8663  diag::err_defaulted_comparison_deduced_return_type_not_auto)
8664  << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8665  << FD->getReturnTypeSourceRange();
8666  return true;
8667  }
8668 
8669  // For a defaulted function in a dependent class, defer all remaining checks
8670  // until instantiation.
8671  if (RD->isDependentType())
8672  return false;
8673 
8674  // Determine whether the function should be defined as deleted.
8675  DefaultedComparisonInfo Info =
8676  DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8677 
8678  bool First = FD == FD->getCanonicalDecl();
8679 
8680  // If we want to delete the function, then do so; there's nothing else to
8681  // check in that case.
8682  if (Info.Deleted) {
8683  if (!First) {
8684  // C++11 [dcl.fct.def.default]p4:
8685  // [For a] user-provided explicitly-defaulted function [...] if such a
8686  // function is implicitly defined as deleted, the program is ill-formed.
8687  //
8688  // This is really just a consequence of the general rule that you can
8689  // only delete a function on its first declaration.
8690  Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8691  << FD->isImplicit() << (int)DCK;
8692  DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8693  DefaultedComparisonAnalyzer::ExplainDeleted)
8694  .visit();
8695  return true;
8696  }
8697 
8698  SetDeclDeleted(FD, FD->getLocation());
8699  if (!inTemplateInstantiation() && !FD->isImplicit()) {
8700  Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8701  << (int)DCK;
8702  DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8703  DefaultedComparisonAnalyzer::ExplainDeleted)
8704  .visit();
8705  }
8706  return false;
8707  }
8708 
8709  // C++2a [class.spaceship]p2:
8710  // The return type is deduced as the common comparison type of R0, R1, ...
8711  if (DCK == DefaultedComparisonKind::ThreeWay &&
8714  if (RetLoc.isInvalid())
8715  RetLoc = FD->getBeginLoc();
8716  // FIXME: Should we really care whether we have the complete type and the
8717  // 'enumerator' constants here? A forward declaration seems sufficient.
8719  Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8720  if (Cat.isNull())
8721  return true;
8723  FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8724  }
8725 
8726  // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8727  // An explicitly-defaulted function that is not defined as deleted may be
8728  // declared constexpr or consteval only if it is constexpr-compatible.
8729  // C++2a [class.compare.default]p3 [P2002R0]:
8730  // A defaulted comparison function is constexpr-compatible if it satisfies
8731  // the requirements for a constexpr function [...]
8732  // The only relevant requirements are that the parameter and return types are
8733  // literal types. The remaining conditions are checked by the analyzer.
8734  if (FD->isConstexpr()) {
8737  !Info.Constexpr) {
8738  Diag(FD->getBeginLoc(),
8739  diag::err_incorrect_defaulted_comparison_constexpr)
8740  << FD->isImplicit() << (int)DCK << FD->isConsteval();
8741  DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8742  DefaultedComparisonAnalyzer::ExplainConstexpr)
8743  .visit();
8744  }
8745  }
8746 
8747  // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8748  // If a constexpr-compatible function is explicitly defaulted on its first
8749  // declaration, it is implicitly considered to be constexpr.
8750  // FIXME: Only applying this to the first declaration seems problematic, as
8751  // simple reorderings can affect the meaning of the program.
8752  if (First && !FD->isConstexpr() && Info.Constexpr)
8754 
8755  // C++2a [except.spec]p3:
8756  // If a declaration of a function does not have a noexcept-specifier
8757  // [and] is defaulted on its first declaration, [...] the exception
8758  // specification is as specified below
8759  if (FD->getExceptionSpecType() == EST_None) {
8760  auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8761  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8763  EPI.ExceptionSpec.SourceDecl = FD;
8764  FD->setType(Context.getFunctionType(FPT->getReturnType(),
8765  FPT->getParamTypes(), EPI));
8766  }
8767 
8768  return false;
8769 }
8770 
8775  Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8776  Ctx.Entity = Spaceship;
8778 
8779  if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8780  EqualEqual->setImplicit();
8781 
8783 }
8784 
8787  assert(FD->isDefaulted() && !FD->isDeleted() &&
8789  if (FD->willHaveBody() || FD->isInvalidDecl())
8790  return;
8791 
8792  SynthesizedFunctionScope Scope(*this, FD);
8793 
8794  // Add a context note for diagnostics produced after this point.
8795  Scope.addContextNote(UseLoc);
8796 
8797  {
8798  // Build and set up the function body.
8799  // The first parameter has type maybe-ref-to maybe-const T, use that to get
8800  // the type of the class being compared.
8801  auto PT = FD->getParamDecl(0)->getType();
8802  CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8803  SourceLocation BodyLoc =
8804  FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8805  StmtResult Body =
8806  DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8807  if (Body.isInvalid()) {
8808  FD->setInvalidDecl();
8809  return;
8810  }
8811  FD->setBody(Body.get());
8812  FD->markUsed(Context);
8813  }
8814 
8815  // The exception specification is needed because we are defining the
8816  // function. Note that this will reuse the body we just built.
8818 
8820  L->CompletedImplicitDefinition(FD);
8821 }
8822 
8825  FunctionDecl *FD,
8827  ComputingExceptionSpec CES(S, FD, Loc);
8829 
8830  if (FD->isInvalidDecl())
8831  return ExceptSpec;
8832 
8833  // The common case is that we just defined the comparison function. In that
8834  // case, just look at whether the body can throw.
8835  if (FD->hasBody()) {
8836  ExceptSpec.CalledStmt(FD->getBody());
8837  } else {
8838  // Otherwise, build a body so we can check it. This should ideally only
8839  // happen when we're not actually marking the function referenced. (This is
8840  // only really important for efficiency: we don't want to build and throw
8841  // away bodies for comparison functions more than we strictly need to.)
8842 
8843  // Pretend to synthesize the function body in an unevaluated context.
8844  // Note that we can't actually just go ahead and define the function here:
8845  // we are not permitted to mark its callees as referenced.
8849 
8850  CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8851  SourceLocation BodyLoc =
8852  FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8853  StmtResult Body =
8854  DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8855  if (!Body.isInvalid())
8856  ExceptSpec.CalledStmt(Body.get());
8857 
8858  // FIXME: Can we hold onto this body and just transform it to potentially
8859  // evaluated when we're asked to define the function rather than rebuilding
8860  // it? Either that, or we should only build the bits of the body that we
8861  // need (the expressions, not the statements).
8862  }
8863 
8864  return ExceptSpec;
8865 }
8866 
8868  decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8870 
8871  std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8873 
8874  // Perform any deferred checking of exception specifications for virtual
8875  // destructors.
8876  for (auto &Check : Overriding)
8877  CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8878 
8879  // Perform any deferred checking of exception specifications for befriended
8880  // special members.
8881  for (auto &Check : Equivalent)
8882  CheckEquivalentExceptionSpec(Check.second, Check.first);
8883 }
8884 
8885 namespace {
8886 /// CRTP base class for visiting operations performed by a special member
8887 /// function (or inherited constructor).
8888 template<typename Derived>
8889 struct SpecialMemberVisitor {
8890  Sema &S;
8891  CXXMethodDecl *MD;
8894 
8895  // Properties of the special member, computed for convenience.
8896  bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8897 
8898  SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8900  : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8901  switch (CSM) {
8905  IsConstructor = true;
8906  break;
8909  IsAssignment = true;
8910  break;
8911  case Sema::CXXDestructor:
8912  break;
8913  case Sema::CXXInvalid:
8914  llvm_unreachable("invalid special member kind");
8915  }
8916 
8917  if (MD->getNumParams()) {
8918  if (const ReferenceType *RT =
8919  MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8920  ConstArg = RT->getPointeeType().isConstQualified();
8921  }
8922  }
8923 
8924  Derived &getDerived() { return static_cast<Derived&>(*this); }
8925 
8926  /// Is this a "move" special member?
8927  bool isMove() const {
8928  return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8929  }
8930 
8931  /// Look up the corresponding special member in the given class.
8933  unsigned Quals, bool IsMutable) {
8934  return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8935  ConstArg && !IsMutable);
8936  }
8937 
8938  /// Look up the constructor for the specified base class to see if it's
8939  /// overridden due to this being an inherited constructor.
8940  Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8941  if (!ICI)
8942  return {};
8943  assert(CSM == Sema::CXXDefaultConstructor);
8944  auto *BaseCtor =
8945  cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8946  if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8947  return MD;
8948  return {};
8949  }
8950 
8951  /// A base or member subobject.
8952  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8953 
8954  /// Get the location to use for a subobject in diagnostics.
8955  static SourceLocation getSubobjectLoc(Subobject Subobj) {
8956  // FIXME: For an indirect virtual base, the direct base leading to
8957  // the indirect virtual base would be a more useful choice.
8958  if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8959  return B->getBaseTypeLoc();
8960  else
8961  return Subobj.get<FieldDecl*>()->getLocation();
8962  }
8963 
8964  enum BasesToVisit {
8965  /// Visit all non-virtual (direct) bases.
8966  VisitNonVirtualBases,
8967  /// Visit all direct bases, virtual or not.
8968  VisitDirectBases,
8969  /// Visit all non-virtual bases, and all virtual bases if the class
8970  /// is not abstract.
8971  VisitPotentiallyConstructedBases,
8972  /// Visit all direct or virtual bases.
8973  VisitAllBases
8974  };
8975 
8976  // Visit the bases and members of the class.
8977  bool visit(BasesToVisit Bases) {
8978  CXXRecordDecl *RD = MD->getParent();
8979 
8980  if (Bases == VisitPotentiallyConstructedBases)
8981  Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8982 
8983  for (auto &B : RD->bases())
8984  if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8985  getDerived().visitBase(&B))
8986  return true;
8987 
8988  if (Bases == VisitAllBases)
8989  for (auto &B : RD->vbases())
8990  if (getDerived().visitBase(&B))
8991  return true;
8992 
8993  for (auto *F : RD->fields())
8994  if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8995  getDerived().visitField(F))
8996  return true;
8997 
8998  return false;
8999  }
9000 };
9001 }
9002 
9003 namespace {
9004 struct SpecialMemberDeletionInfo
9005  : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9006  bool Diagnose;
9007 
9008  SourceLocation Loc;
9009 
9010  bool AllFieldsAreConst;
9011 
9012  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9014  Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9015  : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9016  Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9017 
9018  bool inUnion() const { return MD->getParent()->isUnion(); }
9019 
9020  Sema::CXXSpecialMember getEffectiveCSM() {
9021  return ICI ? Sema::CXXInvalid : CSM;
9022  }
9023 
9024  bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9025 
9026  bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9027  bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9028 
9029  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9030  bool shouldDeleteForField(FieldDecl *FD);
9031  bool shouldDeleteForAllConstMembers();
9032 
9033  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9034  unsigned Quals);
9035  bool shouldDeleteForSubobjectCall(Subobject Subobj,
9037  bool IsDtorCallInCtor);
9038 
9039  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9040 };
9041 }
9042 
9043 /// Is the given special member inaccessible when used on the given
9044 /// sub-object.
9045 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9046  CXXMethodDecl *target) {
9047  /// If we're operating on a base class, the object type is the
9048  /// type of this special member.
9049  QualType objectTy;
9050  AccessSpecifier access = target->getAccess();
9051  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9052  objectTy = S.Context.getTypeDeclType(MD->getParent());
9053  access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9054 
9055  // If we're operating on a field, the object type is the type of the field.
9056  } else {
9057  objectTy = S.Context.getTypeDeclType(target->getParent());
9058  }
9059 
9061  target->getParent(), DeclAccessPair::make(target, access), objectTy);
9062 }
9063 
9064 /// Check whether we should delete a special member due to the implicit
9065 /// definition containing a call to a special member of a subobject.
9066 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9067  Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9068  bool IsDtorCallInCtor) {
9069  CXXMethodDecl *Decl = SMOR.getMethod();
9070  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9071 
9072  int DiagKind = -1;
9073 
9075  DiagKind = !Decl ? 0 : 1;
9077  DiagKind = 2;
9078  else if (!isAccessible(Subobj, Decl))
9079  DiagKind = 3;
9080  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9081  !Decl->isTrivial()) {
9082  // A member of a union must have a trivial corresponding special member.
9083  // As a weird special case, a destructor call from a union's constructor
9084  // must be accessible and non-deleted, but need not be trivial. Such a
9085  // destructor is never actually called, but is semantically checked as
9086  // if it were.
9087  DiagKind = 4;
9088  }
9089 
9090  if (DiagKind == -1)
9091  return false;
9092 
9093  if (Diagnose) {
9094  if (Field) {
9095  S.Diag(Field->getLocation(),
9096  diag::note_deleted_special_member_class_subobject)
9097  << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9098  << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9099  } else {
9100  CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9101  S.Diag(Base->getBeginLoc(),
9102  diag::note_deleted_special_member_class_subobject)
9103  << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9104  << Base->getType() << DiagKind << IsDtorCallInCtor
9105  << /*IsObjCPtr*/false;
9106  }
9107 
9108  if (DiagKind == 1)
9110  // FIXME: Explain inaccessibility if DiagKind == 3.
9111  }
9112 
9113  return true;
9114 }
9115 
9116 /// Check whether we should delete a special member function due to having a
9117 /// direct or virtual base class or non-static data member of class type M.
9118 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9119  CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9120  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9121  bool IsMutable = Field && Field->isMutable();
9122 
9123  // C++11 [class.ctor]p5:
9124  // -- any direct or virtual base class, or non-static data member with no
9125  // brace-or-equal-initializer, has class type M (or array thereof) and
9126  // either M has no default constructor or overload resolution as applied
9127  // to M's default constructor results in an ambiguity or in a function
9128  // that is deleted or inaccessible
9129  // C++11 [class.copy]p11, C++11 [class.copy]p23:
9130  // -- a direct or virtual base class B that cannot be copied/moved because
9131  // overload resolution, as applied to B's corresponding special member,
9132  // results in an ambiguity or a function that is deleted or inaccessible
9133  // from the defaulted special member
9134  // C++11 [class.dtor]p5:
9135  // -- any direct or virtual base class [...] has a type with a destructor
9136  // that is deleted or inaccessible
9137  if (!(CSM == Sema::CXXDefaultConstructor &&
9138  Field && Field->hasInClassInitializer()) &&
9139  shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9140  false))
9141  return true;
9142 
9143  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9144  // -- any direct or virtual base class or non-static data member has a
9145  // type with a destructor that is deleted or inaccessible
9146  if (IsConstructor) {
9149  false, false, false, false, false);
9150  if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9151  return true;
9152  }
9153 
9154  return false;
9155 }
9156 
9157 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9158  FieldDecl *FD, QualType FieldType) {
9159  // The defaulted special functions are defined as deleted if this is a variant
9160  // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9161  // type under ARC.
9162  if (!FieldType.hasNonTrivialObjCLifetime())
9163  return false;
9164 
9165  // Don't make the defaulted default constructor defined as deleted if the
9166  // member has an in-class initializer.
9168  return false;
9169 
9170  if (Diagnose) {
9171  auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9172  S.Diag(FD->getLocation(),
9173  diag::note_deleted_special_member_class_subobject)
9174  << getEffectiveCSM() << ParentClass << /*IsField*/true
9175  << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9176  }
9177 
9178  return true;
9179 }
9180 
9181 /// Check whether we should delete a special member function due to the class
9182 /// having a particular direct or virtual base class.
9183 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9184  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9185  // If program is correct, BaseClass cannot be null, but if it is, the error
9186  // must be reported elsewhere.
9187  if (!BaseClass)
9188  return false;
9189  // If we have an inheriting constructor, check whether we're calling an
9190  // inherited constructor instead of a default constructor.
9191  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9192  if (auto *BaseCtor = SMOR.getMethod()) {
9193  // Note that we do not check access along this path; other than that,
9194  // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9195  // FIXME: Check that the base has a usable destructor! Sink this into
9196  // shouldDeleteForClassSubobject.
9197  if (BaseCtor->isDeleted() && Diagnose) {
9198  S.Diag(Base->getBeginLoc(),
9199  diag::note_deleted_special_member_class_subobject)
9200  << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9201  << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9202  << /*IsObjCPtr*/false;
9203  S.NoteDeletedFunction(BaseCtor);
9204  }
9205  return BaseCtor->isDeleted();
9206  }
9207  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9208 }
9209 
9210 /// Check whether we should delete a special member function due to the class
9211 /// having a particular non-static data member.
9212 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9213  QualType FieldType = S.Context.getBaseElementType(FD->getType());
9214  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9215 
9216  if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9217  return true;
9218 
9219  if (CSM == Sema::CXXDefaultConstructor) {
9220  // For a default constructor, all references must be initialized in-class
9221  // and, if a union, it must have a non-const member.
9222  if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9223  if (Diagnose)
9224  S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9225  << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9226  return true;
9227  }
9228  // C++11 [class.ctor]p5: any non-variant non-static data member of
9229  // const-qualified type (or array thereof) with no
9230  // brace-or-equal-initializer does not have a user-provided default
9231  // constructor.
9232  if (!inUnion() && FieldType.isConstQualified() &&
9233  !FD->hasInClassInitializer() &&
9234  (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9235  if (Diagnose)
9236  S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9237  << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9238  return true;
9239  }
9240 
9241  if (inUnion() && !FieldType.isConstQualified())
9242  AllFieldsAreConst = false;
9243  } else if (CSM == Sema::CXXCopyConstructor) {
9244  // For a copy constructor, data members must not be of rvalue reference
9245  // type.
9246  if (FieldType->isRValueReferenceType()) {
9247  if (Diagnose)
9248  S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9249  << MD->getParent() << FD << FieldType;
9250  return true;
9251  }
9252  } else if (IsAssignment) {
9253  // For an assignment operator, data members must not be of reference type.
9254  if (FieldType->isReferenceType()) {
9255  if (Diagnose)
9256  S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9257  << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9258  return true;
9259  }
9260  if (!FieldRecord && FieldType.isConstQualified()) {
9261  // C++11 [class.copy]p23:
9262  // -- a non-static data member of const non-class type (or array thereof)
9263  if (Diagnose)
9264  S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9265  << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9266  return true;
9267  }
9268  }
9269 
9270  if (FieldRecord) {
9271  // Some additional restrictions exist on the variant members.
9272  if (!inUnion() && FieldRecord->isUnion() &&
9273  FieldRecord->isAnonymousStructOrUnion()) {
9274  bool AllVariantFieldsAreConst = true;
9275 
9276  // FIXME: Handle anonymous unions declared within anonymous unions.
9277  for (auto *UI : FieldRecord->fields()) {
9278  QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9279 
9280  if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9281  return true;
9282 
9283  if (!UnionFieldType.isConstQualified())
9284  AllVariantFieldsAreConst = false;
9285 
9286  CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9287  if (UnionFieldRecord &&
9288  shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9289  UnionFieldType.getCVRQualifiers()))
9290  return true;
9291  }
9292 
9293  // At least one member in each anonymous union must be non-const
9294  if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9295  !FieldRecord->field_empty()) {
9296  if (Diagnose)
9297  S.Diag(FieldRecord->getLocation(),
9298  diag::note_deleted_default_ctor_all_const)
9299  << !!ICI << MD->getParent() << /*anonymous union*/1;
9300  return true;
9301  }
9302 
9303  // Don't check the implicit member of the anonymous union type.
9304  // This is technically non-conformant but supported, and we have a
9305  // diagnostic for this elsewhere.
9306  return false;
9307  }
9308 
9309  if (shouldDeleteForClassSubobject(FieldRecord, FD,
9310  FieldType.getCVRQualifiers()))
9311  return true;
9312  }
9313 
9314  return false;
9315 }
9316 
9317 /// C++11 [class.ctor] p5:
9318 /// A defaulted default constructor for a class X is defined as deleted if
9319 /// X is a union and all of its variant members are of const-qualified type.
9320 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9321  // This is a silly definition, because it gives an empty union a deleted
9322  // default constructor. Don't do that.
9323  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9324  bool AnyFields = false;
9325  for (auto *F : MD->getParent()->fields())
9326  if ((AnyFields = !F->isUnnamedBitfield()))
9327  break;
9328  if (!AnyFields)
9329  return false;
9330  if (Diagnose)
9331  S.Diag(MD->getParent()->getLocation(),
9332  diag::note_deleted_default_ctor_all_const)
9333  << !!ICI << MD->getParent() << /*not anonymous union*/0;
9334  return true;
9335  }
9336  return false;
9337 }
9338 
9339 /// Determine whether a defaulted special member function should be defined as
9340 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9341 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9344  bool Diagnose) {
9345  if (MD->isInvalidDecl())
9346  return false;
9347  CXXRecordDecl *RD = MD->getParent();
9348  assert(!RD->isDependentType() && "do deletion after instantiation");
9349  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9350  return false;
9351 
9352  // C++11 [expr.lambda.prim]p19:
9353  // The closure type associated with a lambda-expression has a
9354  // deleted (8.4.3) default constructor and a deleted copy
9355  // assignment operator.
9356  // C++2a adds back these operators if the lambda has no lambda-capture.
9358  (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9359  if (Diagnose)
9360  Diag(RD->getLocation(), diag::note_lambda_decl);
9361  return true;
9362  }
9363 
9364  // For an anonymous struct or union, the copy and assignment special members
9365  // will never be used, so skip the check. For an anonymous union declared at
9366  // namespace scope, the constructor and destructor are used.
9367  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9369  return false;
9370 
9371  // C++11 [class.copy]p7, p18:
9372  // If the class definition declares a move constructor or move assignment
9373  // operator, an implicitly declared copy constructor or copy assignment
9374  // operator is defined as deleted.
9375  if (MD->isImplicit() &&
9376  (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9377  CXXMethodDecl *UserDeclaredMove = nullptr;
9378 
9379  // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9380  // deletion of the corresponding copy operation, not both copy operations.
9381  // MSVC 2015 has adopted the standards conforming behavior.
9382  bool DeletesOnlyMatchingCopy =
9383  getLangOpts().MSVCCompat &&
9385 
9386  if (RD->hasUserDeclaredMoveConstructor() &&
9387  (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9388  if (!Diagnose) return true;
9389 
9390  // Find any user-declared move constructor.
9391  for (auto *I : RD->ctors()) {
9392  if (I->isMoveConstructor()) {
9393  UserDeclaredMove = I;
9394  break;
9395  }
9396  }
9397  assert(UserDeclaredMove);
9398  } else if (RD->hasUserDeclaredMoveAssignment() &&
9399  (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9400  if (!Diagnose) return true;
9401 
9402  // Find any user-declared move assignment operator.
9403  for (auto *I : RD->methods()) {
9404  if (I->isMoveAssignmentOperator()) {
9405  UserDeclaredMove = I;
9406  break;
9407  }
9408  }
9409  assert(UserDeclaredMove);
9410  }
9411 
9412  if (UserDeclaredMove) {
9413  Diag(UserDeclaredMove->getLocation(),
9414  diag::note_deleted_copy_user_declared_move)
9415  << (CSM == CXXCopyAssignment) << RD
9416  << UserDeclaredMove->isMoveAssignmentOperator();
9417  return true;
9418  }
9419  }
9420 
9421  // Do access control from the special member function
9422  ContextRAII MethodContext(*this, MD);
9423 
9424  // C++11 [class.dtor]p5:
9425  // -- for a virtual destructor, lookup of the non-array deallocation function
9426  // results in an ambiguity or in a function that is deleted or inaccessible
9427  if (CSM == CXXDestructor && MD->isVirtual()) {
9428  FunctionDecl *OperatorDelete = nullptr;
9429  DeclarationName Name =
9431  if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9432  OperatorDelete, /*Diagnose*/false)) {
9433  if (Diagnose)
9434  Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9435  return true;
9436  }
9437  }
9438 
9439  SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9440 
9441  // Per DR1611, do not consider virtual bases of constructors of abstract
9442  // classes, since we are not going to construct them.
9443  // Per DR1658, do not consider virtual bases of destructors of abstract
9444  // classes either.
9445  // Per DR2180, for assignment operators we only assign (and thus only
9446  // consider) direct bases.
9447  if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9448  : SMI.VisitPotentiallyConstructedBases))
9449  return true;
9450 
9451  if (SMI.shouldDeleteForAllConstMembers())
9452  return true;
9453 
9454  if (getLangOpts().CUDA) {
9455  // We should delete the special member in CUDA mode if target inference
9456  // failed.
9457  // For inherited constructors (non-null ICI), CSM may be passed so that MD
9458  // is treated as certain special member, which may not reflect what special
9459  // member MD really is. However inferCUDATargetForImplicitSpecialMember
9460  // expects CSM to match MD, therefore recalculate CSM.
9461  assert(ICI || CSM == getSpecialMember(MD));
9462  auto RealCSM = CSM;
9463  if (ICI)
9464  RealCSM = getSpecialMember(MD);
9465 
9466  return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9467  SMI.ConstArg, Diagnose);
9468  }
9469 
9470  return false;
9471 }
9472 
9475  assert(DFK && "not a defaultable function");
9476  assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9477 
9478  if (DFK.isSpecialMember()) {
9479  ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9480  nullptr, /*Diagnose=*/true);
9481  } else {
9482  DefaultedComparisonAnalyzer(
9483  *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9484  DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9485  .visit();
9486  }
9487 }
9488 
9489 /// Perform lookup for a special member of the specified kind, and determine
9490 /// whether it is trivial. If the triviality can be determined without the
9491 /// lookup, skip it. This is intended for use when determining whether a
9492 /// special member of a containing object is trivial, and thus does not ever
9493 /// perform overload resolution for default constructors.
9494 ///
9495 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9496 /// member that was most likely to be intended to be trivial, if any.
9497 ///
9498 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9499 /// determine whether the special member is trivial.
9501  Sema::CXXSpecialMember CSM, unsigned Quals,
9502  bool ConstRHS,
9504  CXXMethodDecl **Selected) {
9505  if (Selected)
9506  *Selected = nullptr;
9507 
9508  switch (CSM) {
9509  case Sema::CXXInvalid:
9510  llvm_unreachable("not a special member");
9511 
9513  // C++11 [class.ctor]p5:
9514  // A default constructor is trivial if:
9515  // - all the [direct subobjects] have trivial default constructors
9516  //
9517  // Note, no overload resolution is performed in this case.
9518  if (RD->hasTrivialDefaultConstructor())
9519  return true;
9520 
9521  if (Selected) {
9522  // If there's a default constructor which could have been trivial, dig it
9523  // out. Otherwise, if there's any user-provided default constructor, point
9524  // to that as an example of why there's not a trivial one.
9525  CXXConstructorDecl *DefCtor = nullptr;
9528  for (auto *CI : RD->ctors()) {
9529  if (!CI->isDefaultConstructor())
9530  continue;
9531  DefCtor = CI;
9532  if (!DefCtor->isUserProvided())
9533  break;
9534  }
9535 
9536  *Selected = DefCtor;
9537  }
9538 
9539  return false;
9540 
9541  case Sema::CXXDestructor:
9542  // C++11 [class.dtor]p5:
9543  // A destructor is trivial if:
9544  // - all the direct [subobjects] have trivial destructors
9545  if (RD->hasTrivialDestructor() ||
9546  (TAH == Sema::TAH_ConsiderTrivialABI &&
9548  return true;
9549 
9550  if (Selected) {
9551  if (RD->needsImplicitDestructor())
9553  *Selected = RD->getDestructor();
9554  }
9555 
9556  return false;
9557 
9559  // C++11 [class.copy]p12:
9560  // A copy constructor is trivial if:
9561  // - the constructor selected to copy each direct [subobject] is trivial
9562  if (RD->hasTrivialCopyConstructor() ||
9563  (TAH == Sema::TAH_ConsiderTrivialABI &&
9565  if (Quals == Qualifiers::Const)
9566  // We must either select the trivial copy constructor or reach an
9567  // ambiguity; no need to actually perform overload resolution.
9568  return true;
9569  } else if (!Selected) {
9570  return false;
9571  }
9572  // In C++98, we are not supposed to perform overload resolution here, but we
9573  // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9574  // cases like B as having a non-trivial copy constructor:
9575  // struct A { template<typename T> A(T&); };
9576  // struct B { mutable A a; };
9577  goto NeedOverloadResolution;
9578 
9580  // C++11 [class.copy]p25:
9581  // A copy assignment operator is trivial if:
9582  // - the assignment operator selected to copy each direct [subobject] is
9583  // trivial
9584  if (RD->hasTrivialCopyAssignment()) {
9585  if (Quals == Qualifiers::Const)
9586  return true;
9587  } else if (!Selected) {
9588  return false;
9589  }
9590  // In C++98, we are not supposed to perform overload resolution here, but we
9591  // treat that as a language defect.
9592  goto NeedOverloadResolution;
9593 
9596  NeedOverloadResolution:
9598  lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9599 
9600  // The standard doesn't describe how to behave if the lookup is ambiguous.
9601  // We treat it as not making the member non-trivial, just like the standard
9602  // mandates for the default constructor. This should rarely matter, because
9603  // the member will also be deleted.
9605  return true;
9606 
9607  if (!SMOR.getMethod()) {
9608  assert(SMOR.getKind() ==
9610  return false;
9611  }
9612 
9613  // We deliberately don't check if we found a deleted special member. We're
9614  // not supposed to!
9615  if (Selected)
9616  *Selected = SMOR.getMethod();
9617 
9618  if (TAH == Sema::TAH_ConsiderTrivialABI &&
9620  return SMOR.getMethod()->isTrivialForCall();
9621  return SMOR.getMethod()->isTrivial();
9622  }
9623 
9624  llvm_unreachable("unknown special method kind");
9625 }
9626 
9628  for (auto *CI : RD->ctors())
9629  if (!CI->isImplicit())
9630  return CI;
9631 
9632  // Look for constructor templates.
9633  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9634  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9635  if (CXXConstructorDecl *CD =
9636  dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9637  return CD;
9638  }
9639 
9640  return nullptr;
9641 }
9642 
9643 /// The kind of subobject we are checking for triviality. The values of this
9644 /// enumeration are used in diagnostics.
9646  /// The subobject is a base class.
9648  /// The subobject is a non-static data member.
9650  /// The object is actually the complete object.
9652 };
9653 
9654 /// Check whether the special member selected for a given type would be trivial.
9656  QualType SubType, bool ConstRHS,
9659  Sema::TrivialABIHandling TAH, bool Diagnose) {
9660  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9661  if (!SubRD)
9662  return true;
9663 
9664  CXXMethodDecl *Selected;
9665  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9666  ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9667  return true;
9668 
9669  if (Diagnose) {
9670  if (ConstRHS)
9671  SubType.addConst();
9672 
9673  if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9674  S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9675  << Kind << SubType.getUnqualifiedType();
9676  if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9677  S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9678  } else if (!Selected)
9679  S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9680  << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9681  else if (Selected->isUserProvided()) {
9682  if (Kind == TSK_CompleteObject)
9683  S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9684  << Kind << SubType.getUnqualifiedType() << CSM;
9685  else {
9686  S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9687  << Kind << SubType.getUnqualifiedType() << CSM;
9688  S.Diag(Selected->getLocation(), diag::note_declared_at);
9689  }
9690  } else {
9691  if (Kind != TSK_CompleteObject)
9692  S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9693  << Kind << SubType.getUnqualifiedType() << CSM;
9694 
9695  // Explain why the defaulted or deleted special member isn't trivial.
9697  Diagnose);
9698  }
9699  }
9700 
9701  return false;
9702 }
9703 
9704 /// Check whether the members of a class type allow a special member to be
9705 /// trivial.
9708  bool ConstArg,
9710  bool Diagnose) {
9711  for (const auto *FI : RD->fields()) {
9712  if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9713  continue;
9714 
9715  QualType FieldType = S.Context.getBaseElementType(FI->getType());
9716 
9717  // Pretend anonymous struct or union members are members of this class.
9718  if (FI->isAnonymousStructOrUnion()) {
9719  if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9720  CSM, ConstArg, TAH, Diagnose))
9721  return false;
9722  continue;
9723  }
9724 
9725  // C++11 [class.ctor]p5:
9726  // A default constructor is trivial if [...]
9727  // -- no non-static data member of its class has a
9728  // brace-or-equal-initializer
9729  if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9730  if (Diagnose)
9731  S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9732  << FI;
9733  return false;
9734  }
9735 
9736  // Objective C ARC 4.3.5:
9737  // [...] nontrivally ownership-qualified types are [...] not trivially
9738  // default constructible, copy constructible, move constructible, copy
9739  // assignable, move assignable, or destructible [...]
9740  if (FieldType.hasNonTrivialObjCLifetime()) {
9741  if (Diagnose)
9742  S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9743  << RD << FieldType.getObjCLifetime();
9744  return false;
9745  }
9746 
9747  bool ConstRHS = ConstArg && !FI->isMutable();
9748  if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9749  CSM, TSK_Field, TAH, Diagnose))
9750  return false;
9751  }
9752 
9753  return true;
9754 }
9755 
9756 /// Diagnose why the specified class does not have a trivial special member of
9757 /// the given kind.
9759  QualType Ty = Context.getRecordType(RD);
9760 
9761  bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9762  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9764  /*Diagnose*/true);
9765 }
9766 
9767 /// Determine whether a defaulted or deleted special member function is trivial,
9768 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9769 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9771  TrivialABIHandling TAH, bool Diagnose) {
9772  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9773 
9774  CXXRecordDecl *RD = MD->getParent();
9775 
9776  bool ConstArg = false;
9777 
9778  // C++11 [class.copy]p12, p25: [DR1593]
9779  // A [special member] is trivial if [...] its parameter-type-list is
9780  // equivalent to the parameter-type-list of an implicit declaration [...]
9781  switch (CSM) {
9782  case CXXDefaultConstructor:
9783  case CXXDestructor:
9784  // Trivial default constructors and destructors cannot have parameters.
9785  break;
9786 
9787  case CXXCopyConstructor:
9788  case CXXCopyAssignment: {
9789  // Trivial copy operations always have const, non-volatile parameter types.
9790  ConstArg = true;
9791  const ParmVarDecl *Param0 = MD->getParamDecl(0);
9792  const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9793  if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9794  if (Diagnose)
9795  Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9796  << Param0->getSourceRange() << Param0->getType()
9799  return false;
9800  }
9801  break;
9802  }
9803 
9804  case CXXMoveConstructor:
9805  case CXXMoveAssignment: {
9806  // Trivial move operations always have non-cv-qualified parameters.
9807  const ParmVarDecl *Param0 = MD->getParamDecl(0);
9808  const RValueReferenceType *RT =
9809  Param0->getType()->getAs<RValueReferenceType>();
9810  if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9811  if (Diagnose)
9812  Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9813  << Param0->getSourceRange() << Param0->getType()
9815  return false;
9816  }
9817  break;
9818  }
9819 
9820  case CXXInvalid:
9821  llvm_unreachable("not a special member");
9822  }
9823 
9824  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9825  if (Diagnose)
9827  diag::note_nontrivial_default_arg)
9829  return false;
9830  }
9831  if (MD->isVariadic()) {
9832  if (Diagnose)
9833  Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9834  return false;
9835  }
9836 
9837  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9838  // A copy/move [constructor or assignment operator] is trivial if
9839  // -- the [member] selected to copy/move each direct base class subobject
9840  // is trivial
9841  //
9842  // C++11 [class.copy]p12, C++11 [class.copy]p25:
9843  // A [default constructor or destructor] is trivial if
9844  // -- all the direct base classes have trivial [default constructors or
9845  // destructors]
9846  for (const auto &BI : RD->bases())
9847  if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9848  ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9849  return false;
9850 
9851  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9852  // A copy/move [constructor or assignment operator] for a class X is
9853  // trivial if
9854  // -- for each non-static data member of X that is of class type (or array
9855  // thereof), the constructor selected to copy/move that member is
9856  // trivial
9857  //
9858  // C++11 [class.copy]p12, C++11 [class.copy]p25:
9859  // A [default constructor or destructor] is trivial if
9860  // -- for all of the non-static data members of its class that are of class
9861  // type (or array thereof), each such class has a trivial [default
9862  // constructor or destructor]
9863  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9864  return false;
9865 
9866  // C++11 [class.dtor]p5:
9867  // A destructor is trivial if [...]
9868  // -- the destructor is not virtual
9869  if (CSM == CXXDestructor && MD->isVirtual()) {
9870  if (Diagnose)
9871  Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9872  return false;
9873  }
9874 
9875  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9876  // A [special member] for class X is trivial if [...]
9877  // -- class X has no virtual functions and no virtual base classes
9878  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9879  if (!Diagnose)
9880  return false;
9881 
9882  if (RD->getNumVBases()) {
9883  // Check for virtual bases. We already know that the corresponding
9884  // member in all bases is trivial, so vbases must all be direct.
9885  CXXBaseSpecifier &BS = *RD->vbases_begin();
9886  assert(BS.isVirtual());
9887  Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9888  return false;
9889  }
9890 
9891  // Must have a virtual method.
9892  for (const auto *MI : RD->methods()) {
9893  if (MI->isVirtual()) {
9894  SourceLocation MLoc = MI->getBeginLoc();
9895  Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9896  return false;
9897  }
9898  }
9899 
9900  llvm_unreachable("dynamic class with no vbases and no virtual functions");
9901  }
9902 
9903  // Looks like it's trivial!
9904  return true;
9905 }
9906 
9907 namespace {
9908 struct FindHiddenVirtualMethod {
9909  Sema *S;
9910  CXXMethodDecl *Method;
9911  llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9912  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9913 
9914 private:
9915  /// Check whether any most overridden method from MD in Methods
9916  static bool CheckMostOverridenMethods(
9917  const CXXMethodDecl *MD,
9918  const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9919  if (MD->size_overridden_methods() == 0)
9920  return Methods.count(MD->getCanonicalDecl());
9921  for (const CXXMethodDecl *O : MD->overridden_methods())
9922  if (CheckMostOverridenMethods(O, Methods))
9923  return true;
9924  return false;
9925  }
9926 
9927 public:
9928  /// Member lookup function that determines whether a given C++
9929  /// method overloads virtual methods in a base class without overriding any,
9930  /// to be used with CXXRecordDecl::lookupInBases().
9931  bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9932  RecordDecl *BaseRecord =
9933  Specifier->getType()->castAs<RecordType>()->getDecl();
9934 
9935  DeclarationName Name = Method->getDeclName();
9936  assert(Name.getNameKind() == DeclarationName::Identifier);
9937 
9938  bool foundSameNameMethod = false;
9939  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9940  for (Path.Decls = BaseRecord->lookup(Name).begin();
9941  Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9942  NamedDecl *D = *Path.Decls;
9943  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9944  MD = MD->getCanonicalDecl();
9945  foundSameNameMethod = true;
9946  // Interested only in hidden virtual methods.
9947  if (!MD->isVirtual())
9948  continue;
9949  // If the method we are checking overrides a method from its base
9950  // don't warn about the other overloaded methods. Clang deviates from
9951  // GCC by only diagnosing overloads of inherited virtual functions that
9952  // do not override any other virtual functions in the base. GCC's
9953  // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9954  // function from a base class. These cases may be better served by a
9955  // warning (not specific to virtual functions) on call sites when the
9956  // call would select a different function from the base class, were it
9957  // visible.
9958  // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9959  if (!S->IsOverload(Method, MD, false))
9960  return true;
9961  // Collect the overload only if its hidden.
9962  if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9963  overloadedMethods.push_back(MD);
9964  }
9965  }
9966 
9967  if (foundSameNameMethod)
9968  OverloadedMethods.append(overloadedMethods.begin(),
9969  overloadedMethods.end());
9970  return foundSameNameMethod;
9971  }
9972 };
9973 } // end anonymous namespace
9974 
9975 /// Add the most overridden methods from MD to Methods
9977  llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9978  if (MD->size_overridden_methods() == 0)
9979  Methods.insert(MD->getCanonicalDecl());
9980  else
9981  for (const CXXMethodDecl *O : MD->overridden_methods())
9982  AddMostOverridenMethods(O, Methods);
9983 }
9984 
9985 /// Check if a method overloads virtual methods in a base class without
9986 /// overriding any.
9988  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9989  if (!MD->getDeclName().isIdentifier())
9990  return;
9991 
9992  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9993  /*bool RecordPaths=*/false,
9994  /*bool DetectVirtual=*/false);
9995  FindHiddenVirtualMethod FHVM;
9996  FHVM.Method = MD;
9997  FHVM.S = this;
9998 
9999  // Keep the base methods that were overridden or introduced in the subclass
10000  // by 'using' in a set. A base method not in this set is hidden.
10001  CXXRecordDecl *DC = MD->getParent();
10003  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10004  NamedDecl *ND = *I;
10005  if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10006  ND = shad->getTargetDecl();
10007  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10008  AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10009  }
10010 
10011  if (DC->lookupInBases(FHVM, Paths))
10012  OverloadedMethods = FHVM.OverloadedMethods;
10013 }
10014 
10016  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10017  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10018  CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10019  PartialDiagnostic PD = PDiag(
10020  diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10021  HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10022  Diag(overloadedMD->getLocation(), PD);
10023  }
10024 }
10025 
10026 /// Diagnose methods which overload virtual methods in a base class
10027 /// without overriding any.
10029  if (MD->isInvalidDecl())
10030  return;
10031 
10032  if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10033  return;
10034 
10035  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10036  FindHiddenVirtualMethods(MD, OverloadedMethods);
10037  if (!OverloadedMethods.empty()) {
10038  Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10039  << MD << (OverloadedMethods.size() > 1);
10040 
10041  NoteHiddenVirtualMethods(MD, OverloadedMethods);
10042  }
10043 }
10044 
10046  auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10047  // No diagnostics if this is a template instantiation.
10049  Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10050  diag::ext_cannot_use_trivial_abi) << &RD;
10051  Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10052  diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10053  }
10054  RD.dropAttr<TrivialABIAttr>();
10055  };
10056 
10057  // Ill-formed if the copy and move constructors are deleted.
10058  auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10059  // If the type is dependent, then assume it might have
10060  // implicit copy or move ctor because we won't know yet at this point.
10061  if (RD.isDependentType())
10062  return true;
10063  if (RD.needsImplicitCopyConstructor() &&
10065  return true;
10066  if (RD.needsImplicitMoveConstructor() &&
10068  return true;
10069  for (const CXXConstructorDecl *CD : RD.ctors())
10070  if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10071  return true;
10072  return false;
10073  };
10074 
10075  if (!HasNonDeletedCopyOrMoveConstructor()) {
10076  PrintDiagAndRemoveAttr(0);
10077  return;
10078  }
10079 
10080  // Ill-formed if the struct has virtual functions.
10081  if (RD.isPolymorphic()) {
10082  PrintDiagAndRemoveAttr(1);
10083  return;
10084  }
10085 
10086  for (const auto &B : RD.bases()) {
10087  // Ill-formed if the base class is non-trivial for the purpose of calls or a
10088  // virtual base.
10089  if (!B.getType()->isDependentType() &&
10090  !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10091  PrintDiagAndRemoveAttr(2);
10092  return;
10093  }
10094 
10095  if (B.isVirtual()) {
10096  PrintDiagAndRemoveAttr(3);
10097  return;
10098  }
10099  }
10100 
10101  for (const auto *FD : RD.fields()) {
10102  // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10103  // non-trivial for the purpose of calls.
10104  QualType FT = FD->getType();
10105  if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10106  PrintDiagAndRemoveAttr(4);
10107  return;
10108  }
10109 
10110  if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10111  if (!RT->isDependentType() &&
10112  !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10113  PrintDiagAndRemoveAttr(5);
10114  return;
10115  }
10116  }
10117 }
10118 
10120  Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10121  SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10122  if (!TagDecl)
10123  return;
10124 
10126 
10127  for (const ParsedAttr &AL : AttrList) {
10128  if (AL.getKind() != ParsedAttr::AT_Visibility)
10129  continue;
10130  AL.setInvalid();
10131  Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10132  }
10133 
10134  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10135  // strict aliasing violation!
10136  reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10137  FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10138 
10139  CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10140 }
10141 
10142 /// Find the equality comparison functions that should be implicitly declared
10143 /// in a given class definition, per C++2a [class.compare.default]p3.
10145  ASTContext &Ctx, CXXRecordDecl *RD,
10147  DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10148  if (!RD->lookup(EqEq).empty())
10149  // Member operator== explicitly declared: no implicit operator==s.
10150  return;
10151 
10152  // Traverse friends looking for an '==' or a '<=>'.
10153  for (FriendDecl *Friend : RD->friends()) {
10154  FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10155  if (!FD) continue;
10156 
10157  if (FD->getOverloadedOperator() == OO_EqualEqual) {
10158  // Friend operator== explicitly declared: no implicit operator==s.
10159  Spaceships.clear();
10160  return;
10161  }
10162 
10163  if (FD->getOverloadedOperator() == OO_Spaceship &&
10164  FD->isExplicitlyDefaulted())
10165  Spaceships.push_back(FD);
10166  }
10167 
10168  // Look for members named 'operator<=>'.
10169  DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10170  for (NamedDecl *ND : RD->lookup(Cmp)) {
10171  // Note that we could find a non-function here (either a function template
10172  // or a using-declaration). Neither case results in an implicit
10173  // 'operator=='.
10174  if (auto *FD = dyn_cast<FunctionDecl>(ND))
10175  if (FD->isExplicitlyDefaulted())
10176  Spaceships.push_back(FD);
10177  }
10178 }
10179 
10180 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10181 /// special functions, such as the default constructor, copy
10182 /// constructor, or destructor, to the given C++ class (C++
10183 /// [special]p1). This routine can only be executed just before the
10184 /// definition of the class is complete.
10186  // Don't add implicit special members to templated classes.
10187  // FIXME: This means unqualified lookups for 'operator=' within a class
10188  // template don't work properly.
10189  if (!ClassDecl->isDependentType()) {
10190  if (ClassDecl->needsImplicitDefaultConstructor()) {
10192 
10193  if (ClassDecl->hasInheritedConstructor())
10195  }
10196 
10197  if (ClassDecl->needsImplicitCopyConstructor()) {
10199 
10200  // If the properties or semantics of the copy constructor couldn't be
10201  // determined while the class was being declared, force a declaration
10202  // of it now.
10203  if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10204  ClassDecl->hasInheritedConstructor())
10205  DeclareImplicitCopyConstructor(ClassDecl);
10206  // For the MS ABI we need to know whether the copy ctor is deleted. A
10207  // prerequisite for deleting the implicit copy ctor is that the class has
10208  // a move ctor or move assignment that is either user-declared or whose
10209  // semantics are inherited from a subobject. FIXME: We should provide a
10210  // more direct way for CodeGen to ask whether the constructor was deleted.
10211  else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10212  (ClassDecl->hasUserDeclaredMoveConstructor() ||
10214  ClassDecl->hasUserDeclaredMoveAssignment() ||
10216  DeclareImplicitCopyConstructor(ClassDecl);
10217  }
10218 
10219  if (getLangOpts().CPlusPlus11 &&
10220  ClassDecl->needsImplicitMoveConstructor()) {
10222 
10223  if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10224  ClassDecl->hasInheritedConstructor())
10225  DeclareImplicitMoveConstructor(ClassDecl);
10226  }
10227 
10228  if (ClassDecl->needsImplicitCopyAssignment()) {
10230 
10231  // If we have a dynamic class, then the copy assignment operator may be
10232  // virtual, so we have to declare it immediately. This ensures that, e.g.,
10233  // it shows up in the right place in the vtable and that we diagnose
10234  // problems with the implicit exception specification.
10235  if (ClassDecl->isDynamicClass() ||
10237  ClassDecl->hasInheritedAssignment())
10238  DeclareImplicitCopyAssignment(ClassDecl);
10239  }
10240 
10241  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10243 
10244  // Likewise for the move assignment operator.
10245  if (ClassDecl->isDynamicClass() ||
10247  ClassDecl->hasInheritedAssignment())
10248  DeclareImplicitMoveAssignment(ClassDecl);
10249  }
10250 
10251  if (ClassDecl->needsImplicitDestructor()) {
10253 
10254  // If we have a dynamic class, then the destructor may be virtual, so we
10255  // have to declare the destructor immediately. This ensures that, e.g., it
10256  // shows up in the right place in the vtable and that we diagnose problems
10257  // with the implicit exception specification.
10258  if (ClassDecl->isDynamicClass() ||
10260  DeclareImplicitDestructor(ClassDecl);
10261  }
10262  }
10263 
10264  // C++2a [class.compare.default]p3:
10265  // If the member-specification does not explicitly declare any member or
10266  // friend named operator==, an == operator function is declared implicitly
10267  // for each defaulted three-way comparison operator function defined in
10268  // the member-specification
10269  // FIXME: Consider doing this lazily.
10270  // We do this during the initial parse for a class template, not during
10271  // instantiation, so that we can handle unqualified lookups for 'operator=='
10272  // when parsing the template.
10274  llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10276  DefaultedSpaceships);
10277  for (auto *FD : DefaultedSpaceships)
10278  DeclareImplicitEqualityComparison(ClassDecl, FD);
10279  }
10280 }
10281 
10282 unsigned
10284  llvm::function_ref<Scope *()> EnterScope) {
10285  if (!D)
10286  return 0;
10288 
10289  // In order to get name lookup right, reenter template scopes in order from
10290  // outermost to innermost.
10292  DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10293 
10294  if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10295  for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10296  ParameterLists.push_back(DD->getTemplateParameterList(i));
10297 
10298  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10299  if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10300  ParameterLists.push_back(FTD->getTemplateParameters());
10301  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10302  LookupDC = VD->getDeclContext();
10303 
10304  if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10305  ParameterLists.push_back(VTD->getTemplateParameters());
10306  else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10307  ParameterLists.push_back(PSD->getTemplateParameters());
10308  }
10309  } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10310  for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10311  ParameterLists.push_back(TD->getTemplateParameterList(i));
10312 
10313  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10315  ParameterLists.push_back(CTD->getTemplateParameters());
10316  else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10317  ParameterLists.push_back(PSD->getTemplateParameters());
10318  }
10319  }
10320  // FIXME: Alias declarations and concepts.
10321 
10322  unsigned Count = 0;
10323  Scope *InnermostTemplateScope = nullptr;
10324  for (TemplateParameterList *Params : ParameterLists) {
10325  // Ignore explicit specializations; they don't contribute to the template
10326  // depth.
10327  if (Params->size() == 0)
10328  continue;
10329 
10330  InnermostTemplateScope = EnterScope();
10331  for (NamedDecl *Param : *Params) {
10332  if (Param->getDeclName()) {
10333  InnermostTemplateScope->AddDecl(Param);
10334  IdResolver.AddDecl(Param);
10335  }
10336  }
10337  ++Count;
10338  }
10339 
10340  // Associate the new template scopes with the corresponding entities.
10341  if (InnermostTemplateScope) {
10342  assert(LookupDC && "no enclosing DeclContext for template lookup");
10343  EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10344  }
10345 
10346  return Count;
10347 }
10348 
10350  if (!RecordD) return;
10351  AdjustDeclIfTemplate(RecordD);
10352  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10353  PushDeclContext(S, Record);
10354 }
10355 
10357  if (!RecordD) return;
10358  PopDeclContext();
10359 }
10360 
10361 /// This is used to implement the constant expression evaluation part of the
10362 /// attribute enable_if extension. There is nothing in standard C++ which would
10363 /// require reentering parameters.
10365  if (!Param)
10366  return;
10367 
10368  S->AddDecl(Param);
10369  if (Param->getDeclName())
10370  IdResolver.AddDecl(Param);
10371 }
10372 
10373 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10374 /// parsing a top-level (non-nested) C++ class, and we are now
10375 /// parsing those parts of the given Method declaration that could
10376 /// not be parsed earlier (C++ [class.mem]p2), such as default
10377 /// arguments. This action should enter the scope of the given
10378 /// Method declaration as if we had just parsed the qualified method
10379 /// name. However, it should not bring the parameters into scope;
10380 /// that will be performed by ActOnDelayedCXXMethodParameter.
10382 }
10383 
10384 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10385 /// C++ method declaration. We're (re-)introducing the given
10386 /// function parameter into scope for use in parsing later parts of
10387 /// the method declaration. For example, we could see an
10388 /// ActOnParamDefaultArgument event for this parameter.
10390  if (!ParamD)
10391  return;
10392 
10393  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10394 
10395  S->AddDecl(Param);
10396  if (Param->getDeclName())
10397  IdResolver.AddDecl(Param);
10398 }
10399 
10400 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10401 /// processing the delayed method declaration for Method. The method
10402 /// declaration is now considered finished. There may be a separate
10403 /// ActOnStartOfFunctionDef action later (not necessarily
10404 /// immediately!) for this method, if it was also defined inside the
10405 /// class body.
10407  if (!MethodD)
10408  return;
10409 
10410  AdjustDeclIfTemplate(MethodD);
10411 
10412  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10413 
10414  // Now that we have our default arguments, check the constructor
10415  // again. It could produce additional diagnostics or affect whether
10416  // the class has implicitly-declared destructors, among other
10417  // things.
10418  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10419  CheckConstructor(Constructor);
10420 
10421  // Check the default arguments, which we may have added.
10422  if (!Method->isInvalidDecl())
10423  CheckCXXDefaultArguments(Method);
10424 }
10425 
10426 // Emit the given diagnostic for each non-address-space qualifier.
10427 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10428 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10430  if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10431  bool DiagOccured = false;
10433  [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10434  SourceLocation SL) {
10435  // This diagnostic should be emitted on any qualifier except an addr
10436  // space qualifier. However, forEachQualifier currently doesn't visit
10437  // addr space qualifiers, so there's no way to write this condition
10438  // right now; we just diagnose on everything.
10439  S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10440  DiagOccured = true;
10441  });
10442  if (DiagOccured)
10443  D.setInvalidType();
10444  }
10445 }
10446 
10447 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10448 /// the well-formedness of the constructor declarator @p D with type @p
10449 /// R. If there are any errors in the declarator, this routine will
10450 /// emit diagnostics and set the invalid bit to true. In any case, the type
10451 /// will be updated to reflect a well-formed type for the constructor and
10452 /// returned.
10454  StorageClass &SC) {
10455  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10456 
10457  // C++ [class.ctor]p3:
10458  // A constructor shall not be virtual (10.3) or static (9.4). A
10459  // constructor can be invoked for a const, volatile or const
10460  // volatile object. A constructor shall not be declared const,
10461  // volatile, or const volatile (9.3.2).
10462  if (isVirtual) {
10463  if (!D.isInvalidType())
10464  Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10465  << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10466  << SourceRange(D.getIdentifierLoc());
10467  D.setInvalidType();
10468  }
10469  if (SC == SC_Static) {
10470  if (!D.isInvalidType())
10471  Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10472  << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10473  << SourceRange(D.getIdentifierLoc());
10474  D.setInvalidType();
10475  SC = SC_None;
10476  }
10477 
10478  if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10480  diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10484  D.setInvalidType();
10485  }
10486 
10487  checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10488 
10489  // C++0x [class.ctor]p4:
10490  // A constructor shall not be declared with a ref-qualifier.
10492  if (FTI.hasRefQualifier()) {
10493  Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10496  D.setInvalidType();
10497  }
10498 
10499  // Rebuild the function type "R" without any type qualifiers (in
10500  // case any of the errors above fired) and with "void" as the
10501  // return type, since constructors don't have return types.
10502  const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10503  if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10504  return R;
10505 
10507  EPI.TypeQuals = Qualifiers();
10508  EPI.RefQualifier = RQ_None;
10509 
10510  return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10511 }
10512 
10513 /// CheckConstructor - Checks a fully-formed constructor for
10514 /// well-formedness, issuing any diagnostics required. Returns true if
10515 /// the constructor declarator is invalid.
10517  CXXRecordDecl *ClassDecl
10518  = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10519  if (!ClassDecl)
10520  return Constructor->setInvalidDecl();
10521 
10522  // C++ [class.copy]p3:
10523  // A declaration of a constructor for a class X is ill-formed if
10524  // its first parameter is of type (optionally cv-qualified) X and
10525  // either there are no other parameters or else all other
10526  // parameters have default arguments.
10527  if (!Constructor->isInvalidDecl() &&
10528  Constructor->hasOneParamOrDefaultArgs() &&
10529  Constructor->getTemplateSpecializationKind() !=
10531  QualType ParamType = Constructor->getParamDecl(0)->getType();
10532  QualType ClassTy = Context.getTagDeclType(ClassDecl);
10533  if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10534  SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10535  const char *ConstRef
10536  = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10537  : " const &";
10538  Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10539  << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10540 
10541  // FIXME: Rather that making the constructor invalid, we should endeavor
10542  // to fix the type.
10543  Constructor->setInvalidDecl();
10544  }
10545  }
10546 }
10547 
10548 /// CheckDestructor - Checks a fully-formed destructor definition for
10549 /// well-formedness, issuing any diagnostics required. Returns true
10550 /// on error.
10552  CXXRecordDecl *RD = Destructor->getParent();
10553 
10554  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10555  SourceLocation Loc;
10556 
10557  if (!Destructor->isImplicit())
10558  Loc = Destructor->getLocation();
10559  else
10560  Loc = RD->getLocation();
10561 
10562  // If we have a virtual destructor, look up the deallocation function
10563  if (FunctionDecl *OperatorDelete =
10565  Expr *ThisArg = nullptr;
10566 
10567  // If the notional 'delete this' expression requires a non-trivial
10568  // conversion from 'this' to the type of a destroying operator delete's
10569  // first parameter, perform that conversion now.
10570  if (OperatorDelete->isDestroyingOperatorDelete()) {
10571  QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10572  if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10573  // C++ [class.dtor]p13:
10574  // ... as if for the expression 'delete this' appearing in a
10575  // non-virtual destructor of the destructor's class.
10576  ContextRAII SwitchContext(*this, Destructor);
10577  ExprResult This =
10578  ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10579  assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10580  This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10581  if (This.isInvalid()) {
10582  // FIXME: Register this as a context note so that it comes out
10583  // in the right order.
10584  Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10585  return true;
10586  }
10587  ThisArg = This.get();
10588  }
10589  }
10590 
10591  DiagnoseUseOfDecl(OperatorDelete, Loc);
10592  MarkFunctionReferenced(Loc, OperatorDelete);
10593  Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10594  }
10595  }
10596 
10597  return false;
10598 }
10599 
10600 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10601 /// the well-formednes of the destructor declarator @p D with type @p
10602 /// R. If there are any errors in the declarator, this routine will
10603 /// emit diagnostics and set the declarator to invalid. Even if this happens,
10604 /// will be updated to reflect a well-formed type for the destructor and
10605 /// returned.
10607  StorageClass& SC) {
10608  // C++ [class.dtor]p1:
10609  // [...] A typedef-name that names a class is a class-name
10610  // (7.1.3); however, a typedef-name that names a class shall not
10611  // be used as the identifier in the declarator for a destructor
10612  // declaration.
10613  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10614  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10615  Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10616  << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10617  else if (const TemplateSpecializationType *TST =
10618  DeclaratorType->getAs<TemplateSpecializationType>())
10619  if (TST->isTypeAlias())
10620  Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10621  << DeclaratorType << 1;
10622 
10623  // C++ [class.dtor]p2:
10624  // A destructor is used to destroy objects of its class type. A
10625  // destructor takes no parameters, and no return type can be
10626  // specified for it (not even void). The address of a destructor
10627  // shall not be taken. A destructor shall not be static. A
10628  // destructor can be invoked for a const, volatile or const
10629  // volatile object. A destructor shall not be declared const,
10630  // volatile or const volatile (9.3.2).
10631  if (SC == SC_Static) {
10632  if (!D.isInvalidType())
10633  Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10634  << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10637 
10638  SC = SC_None;
10639  }
10640  if (!D.isInvalidType()) {
10641  // Destructors don't have return types, but the parser will
10642  // happily parse something like:
10643  //
10644  // class X {
10645  // float ~X();
10646  // };
10647  //
10648  // The return type will be eliminated later.
10649  if (D.getDeclSpec().hasTypeSpecifier())
10650  Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10652  << SourceRange(D.getIdentifierLoc());
10653  else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10654  diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10655  SourceLocation(),
10660  D.setInvalidType();
10661  }
10662  }
10663 
10664  checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10665 
10666  // C++0x [class.dtor]p2:
10667  // A destructor shall not be declared with a ref-qualifier.
10669  if (FTI.hasRefQualifier()) {
10670  Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10673  D.setInvalidType();
10674  }
10675 
10676  // Make sure we don't have any parameters.
10677  if (FTIHasNonVoidParameters(FTI)) {
10678  Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10679 
10680  // Delete the parameters.
10681  FTI.freeParams();
10682  D.setInvalidType();
10683  }
10684 
10685  // Make sure the destructor isn't variadic.
10686  if (FTI.isVariadic) {
10687  Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10688  D.setInvalidType();
10689  }
10690 
10691  // Rebuild the function type "R" without any type qualifiers or
10692  // parameters (in case any of the errors above fired) and with
10693  // "void" as the return type, since destructors don't have return
10694  // types.
10695  if (!D.isInvalidType())
10696  return R;
10697 
10698  const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10700  EPI.Variadic = false;
10701  EPI.TypeQuals = Qualifiers();
10702  EPI.RefQualifier = RQ_None;
10703  return Context.getFunctionType(Context.VoidTy, None, EPI);
10704 }
10705 
10706 static void extendLeft(SourceRange &R, SourceRange Before) {
10707  if (Before.isInvalid())
10708  return;
10709  R.setBegin(Before.getBegin());
10710  if (R.getEnd().isInvalid())
10711  R.setEnd(Before.getEnd());
10712 }
10713 
10715  if (After.isInvalid())
10716  return;
10717  if (R.getBegin().isInvalid())
10718  R.setBegin(After.getBegin());
10719  R.setEnd(After.getEnd());
10720 }
10721 
10722 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10723 /// well-formednes of the conversion function declarator @p D with
10724 /// type @p R. If there are any errors in the declarator, this routine
10725 /// will emit diagnostics and return true. Otherwise, it will return
10726 /// false. Either way, the type @p R will be updated to reflect a
10727 /// well-formed type for the conversion operator.
10729  StorageClass& SC) {
10730  // C++ [class.conv.fct]p1:
10731  // Neither parameter types nor return type can be specified. The
10732  // type of a conversion function (8.3.5) is "function taking no
10733  // parameter returning conversion-type-id."
10734  if (SC == SC_Static) {
10735  if (!D.isInvalidType())
10736  Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10738  << D.getName().getSourceRange();
10739  D.setInvalidType();
10740  SC = SC_None;
10741  }
10742 
10743  TypeSourceInfo *ConvTSI = nullptr;
10744  QualType ConvType =
10746 
10747  const DeclSpec &DS = D.getDeclSpec();
10748  if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10749  // Conversion functions don't have return types, but the parser will
10750  // happily parse something like:
10751  //
10752  // class X {
10753  // float operator bool();
10754  // };
10755  //
10756  // The return type will be changed later anyway.
10757  Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10759  << SourceRange(D.getIdentifierLoc());
10760  D.setInvalidType();
10761  } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10762  // It's also plausible that the user writes type qualifiers in the wrong
10763  // place, such as:
10764  // struct S { const operator int(); };
10765  // FIXME: we could provide a fixit to move the qualifiers onto the
10766  // conversion type.
10767  Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10768  << SourceRange(D.getIdentifierLoc()) << 0;
10769  D.setInvalidType();
10770  }
10771 
10772  const auto *Proto = R->castAs<FunctionProtoType>();
10773 
10774  // Make sure we don't have any parameters.
10775  if (Proto->getNumParams() > 0) {
10776  Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10777 
10778  // Delete the parameters.
10780  D.setInvalidType();
10781  } else if (Proto->isVariadic()) {
10782  Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10783  D.setInvalidType();
10784  }
10785 
10786  // Diagnose "&operator bool()" and other such nonsense. This
10787  // is actually a gcc extension which we don't support.
10788  if (Proto->getReturnType() != ConvType) {
10789  bool NeedsTypedef = false;
10790  SourceRange Before, After;
10791 
10792  // Walk the chunks and extract information on them for our diagnostic.
10793  bool PastFunctionChunk = false;
10794  for (auto &Chunk : D.type_objects()) {
10795  switch (Chunk.Kind) {
10797  if (!PastFunctionChunk) {
10798  if (Chunk.Fun.HasTrailingReturnType) {
10799  TypeSourceInfo *TRT = nullptr;
10800  GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10801  if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10802  }
10803  PastFunctionChunk = true;
10804  break;
10805  }
10806  LLVM_FALLTHROUGH;
10808  NeedsTypedef = true;
10809  extendRight(After, Chunk.getSourceRange());
10810  break;
10811 
10816  case DeclaratorChunk::Pipe:
10817  extendLeft(Before, Chunk.getSourceRange());
10818  break;
10819 
10821  extendLeft(Before, Chunk.Loc);
10822  extendRight(After, Chunk.EndLoc);
10823  break;
10824  }
10825  }
10826 
10827  SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10828  After.isValid() ? After.getBegin() :
10829  D.getIdentifierLoc();
10830  auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10831  DB << Before << After;
10832 
10833  if (!NeedsTypedef) {
10834  DB << /*don't need a typedef*/0;
10835 
10836  // If we can provide a correct fix-it hint, do so.
10837  if (After.isInvalid() && ConvTSI) {
10838  SourceLocation InsertLoc =
10840  DB << FixItHint::CreateInsertion(InsertLoc, " ")
10842  InsertLoc, CharSourceRange::getTokenRange(Before))
10843  << FixItHint::CreateRemoval(Before);
10844  }
10845  } else if (!Proto->getReturnType()->isDependentType()) {
10846  DB << /*typedef*/1 << Proto->getReturnType();
10847  } else if (getLangOpts().CPlusPlus11) {
10848  DB << /*alias template*/2 << Proto->getReturnType();
10849  } else {
10850  DB << /*might not be fixable*/3;
10851  }
10852 
10853  // Recover by incorporating the other type chunks into the result type.
10854  // Note, this does *not* change the name of the function. This is compatible
10855  // with the GCC extension:
10856  // struct S { &operator int(); } s;
10857  // int &r = s.operator int(); // ok in GCC
10858  // S::operator int&() {} // error in GCC, function name is 'operator int'.
10859  ConvType = Proto->getReturnType();
10860  }
10861 
10862  // C++ [class.conv.fct]p4:
10863  // The conversion-type-id shall not represent a function type nor
10864  // an array type.
10865  if (ConvType->isArrayType()) {
10866  Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10867  ConvType = Context.getPointerType(ConvType);
10868  D.setInvalidType();
10869  } else if (ConvType->isFunctionType()) {
10870  Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10871  ConvType = Context.getPointerType(ConvType);
10872  D.setInvalidType();
10873  }
10874 
10875  // Rebuild the function type "R" without any parameters (in case any
10876  // of the errors above fired) and with the conversion type as the
10877  // return type.
10878  if (D.isInvalidType())
10879  R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10880 
10881  // C++0x explicit conversion operators.
10883  Diag(DS.getExplicitSpecLoc(),
10885  ? diag::warn_cxx98_compat_explicit_conversion_functions
10886  : diag::ext_explicit_conversion_functions)
10888 }
10889 
10890 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10891 /// the declaration of the given C++ conversion function. This routine
10892 /// is responsible for recording the conversion function in the C++
10893 /// class, if possible.
10895  assert(Conversion && "Expected to receive a conversion function declaration");
10896 
10897  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10898 
10899  // Make sure we aren't redeclaring the conversion function.
10900  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10901  // C++ [class.conv.fct]p1:
10902  // [...] A conversion function is never used to convert a
10903  // (possibly cv-qualified) object to the (possibly cv-qualified)
10904  // same object type (or a reference to it), to a (possibly
10905  // cv-qualified) base class of that type (or a reference to it),
10906  // or to (possibly cv-qualified) void.
10907  QualType ClassType
10909  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10910  ConvType = ConvTypeRef->getPointeeType();
10911  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10913  /* Suppress diagnostics for instantiations. */;
10914  else if (Conversion->size_overridden_methods() != 0)
10915  /* Suppress diagnostics for overriding virtual function in a base class. */;
10916  else if (ConvType->isRecordType()) {
10917  ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10918  if (ConvType == ClassType)
10919  Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10920  << ClassType;
10921  else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10922  Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10923  << ClassType << ConvType;
10924  } else if (ConvType->isVoidType()) {
10925  Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10926  << ClassType << ConvType;
10927  }
10928 
10929  if (FunctionTemplateDecl *ConversionTemplate
10930  = Conversion->getDescribedFunctionTemplate())
10931  return ConversionTemplate;
10932 
10933  return Conversion;
10934 }
10935 
10936 namespace {
10937 /// Utility class to accumulate and print a diagnostic listing the invalid
10938 /// specifier(s) on a declaration.
10939 struct BadSpecifierDiagnoser {
10940  BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10941  : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10942  ~BadSpecifierDiagnoser() {
10943  Diagnostic << Specifiers;
10944  }
10945 
10946  template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10947  return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10948  }
10949  void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10950  return check(SpecLoc,
10952  }
10953  void check(SourceLocation SpecLoc, const char *Spec) {
10954  if (SpecLoc.isInvalid()) return;
10955  Diagnostic << SourceRange(SpecLoc, SpecLoc);
10956  if (!Specifiers.empty()) Specifiers += " ";
10957  Specifiers += Spec;
10958  }
10959 
10960  Sema &S;
10962  std::string Specifiers;
10963 };
10964 }
10965 
10966 /// Check the validity of a declarator that we parsed for a deduction-guide.
10967 /// These aren't actually declarators in the grammar, so we need to check that
10968 /// the user didn't specify any pieces that are not part of the deduction-guide
10969 /// grammar.
10971  StorageClass &SC) {
10972  TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10973  TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10974  assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10975 
10976  // C++ [temp.deduct.guide]p3:
10977  // A deduction-gide shall be declared in the same scope as the
10978  // corresponding class template.
10980  GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10981  Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10982  << GuidedTemplateDecl;
10983  Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10984  }
10985 
10986  auto &DS = D.getMutableDeclSpec();
10987  // We leave 'friend' and 'virtual' to be rejected in the normal way.
10988  if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10989  DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10990  DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10991  BadSpecifierDiagnoser Diagnoser(
10992  *this, D.getIdentifierLoc(),
10993  diag::err_deduction_guide_invalid_specifier);
10994 
10995  Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10996  DS.ClearStorageClassSpecs();
10997  SC = SC_None;
10998 
10999  // 'explicit' is permitted.
11000  Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11001  Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11002  Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11003  DS.ClearConstexprSpec();
11004 
11005  Diagnoser.check(DS.getConstSpecLoc(), "const");
11006  Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11007  Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11008  Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11009  Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11010  DS.ClearTypeQualifiers();
11011 
11012  Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11013  Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11014  Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11015  Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11016  DS.ClearTypeSpecType();
11017  }
11018 
11019  if (D.isInvalidType())
11020  return;
11021 
11022  // Check the declarator is simple enough.
11023  bool FoundFunction = false;
11024  for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11025  if (Chunk.Kind == DeclaratorChunk::Paren)
11026  continue;
11027  if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11029  diag::err_deduction_guide_with_complex_decl)
11030  << D.getSourceRange();
11031  break;
11032  }
11033  if (!Chunk.Fun.hasTrailingReturnType()) {
11034  Diag(D.getName().getBeginLoc(),
11035  diag::err_deduction_guide_no_trailing_return_type);
11036  break;
11037  }
11038 
11039  // Check that the return type is written as a specialization of
11040  // the template specified as the deduction-guide's name.
11041  ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11042  TypeSourceInfo *TSI = nullptr;
11043  QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11044  assert(TSI && "deduction guide has valid type but invalid return type?");
11045  bool AcceptableReturnType = false;
11046  bool MightInstantiateToSpecialization = false;
11047  if (auto RetTST =
11049  TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11050  bool TemplateMatches =
11051  Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11052  if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
11053  AcceptableReturnType = true;
11054  else {
11055  // This could still instantiate to the right type, unless we know it
11056  // names the wrong class template.
11057  auto *TD = SpecifiedName.getAsTemplateDecl();
11058  MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11059  !TemplateMatches);
11060  }
11061  } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11062  MightInstantiateToSpecialization = true;
11063  }
11064 
11065  if (!AcceptableReturnType) {
11066  Diag(TSI->getTypeLoc().getBeginLoc(),
11067  diag::err_deduction_guide_bad_trailing_return_type)
11068  << GuidedTemplate << TSI->getType()
11069  << MightInstantiateToSpecialization
11070  << TSI->getTypeLoc().getSourceRange();
11071  }
11072 
11073  // Keep going to check that we don't have any inner declarator pieces (we
11074  // could still have a function returning a pointer to a function).
11075  FoundFunction = true;
11076  }
11077 
11078  if (D.isFunctionDefinition())
11079  Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11080 }
11081 
11082 //===----------------------------------------------------------------------===//
11083 // Namespace Handling
11084 //===----------------------------------------------------------------------===//
11085 
11086 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11087 /// reopened.
11089  SourceLocation Loc,
11090  IdentifierInfo *II, bool *IsInline,
11091  NamespaceDecl *PrevNS) {
11092  assert(*IsInline != PrevNS->isInline());
11093 
11094  // 'inline' must appear on the original definition, but not necessarily
11095  // on all extension definitions, so the note should point to the first
11096  // definition to avoid confusion.
11097  PrevNS = PrevNS->getFirstDecl();
11098 
11099  if (PrevNS->isInline())
11100  // The user probably just forgot the 'inline', so suggest that it
11101  // be added back.
11102  S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11103  << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11104  else
11105  S.Diag(Loc, diag::err_inline_namespace_mismatch);
11106 
11107  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11108  *IsInline = PrevNS->isInline();
11109 }
11110 
11111 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11112 /// definition.
11114  Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11115  SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11116  const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11117  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11118  // For anonymous namespace, take the location of the left brace.
11119  SourceLocation Loc = II ? IdentLoc : LBrace;
11120  bool IsInline = InlineLoc.isValid();
11121  bool IsInvalid = false;
11122  bool IsStd = false;
11123  bool AddToKnown = false;
11124  Scope *DeclRegionScope = NamespcScope->getParent();
11125 
11126  NamespaceDecl *PrevNS = nullptr;
11127  if (II) {
11128  // C++ [namespace.def]p2:
11129  // The identifier in an original-namespace-definition shall not
11130  // have been previously defined in the declarative region in
11131  // which the original-namespace-definition appears. The
11132  // identifier in an original-namespace-definition is the name of
11133  // the namespace. Subsequently in that declarative region, it is
11134  // treated as an original-namespace-name.
11135  //
11136  // Since namespace names are unique in their scope, and we don't
11137  // look through using directives, just look for any ordinary names
11138  // as if by qualified name lookup.
11139  LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11142  NamedDecl *PrevDecl =
11143  R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11144  PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11145 
11146  if (PrevNS) {
11147  // This is an extended namespace definition.
11148  if (IsInline != PrevNS->isInline())
11149  DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11150  &IsInline, PrevNS);
11151  } else if (PrevDecl) {
11152  // This is an invalid name redefinition.
11153  Diag(Loc, diag::err_redefinition_different_kind)
11154  << II;
11155  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11156  IsInvalid = true;
11157  // Continue on to push Namespc as current DeclContext and return it.
11158  } else if (II->isStr("std") &&
11160  // This is the first "real" definition of the namespace "std", so update
11161  // our cache of the "std" namespace to point at this definition.
11162  PrevNS = getStdNamespace();
11163  IsStd = true;
11164  AddToKnown = !IsInline;
11165  } else {
11166  // We've seen this namespace for the first time.
11167  AddToKnown = !IsInline;
11168  }
11169  } else {
11170  // Anonymous namespaces.
11171 
11172  // Determine whether the parent already has an anonymous namespace.
11174  if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11175  PrevNS = TU->getAnonymousNamespace();
11176  } else {
11177  NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11178  PrevNS = ND->getAnonymousNamespace();
11179  }
11180 
11181  if (PrevNS && IsInline != PrevNS->isInline())
11182  DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11183  &IsInline, PrevNS);
11184  }
11185 
11186  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11187  StartLoc, Loc, II, PrevNS);
11188  if (IsInvalid)
11189  Namespc->setInvalidDecl();
11190 
11191  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11192  AddPragmaAttributes(DeclRegionScope, Namespc);
11193 
11194  // FIXME: Should we be merging attributes?
11195  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11197 
11198  if (IsStd)
11199  StdNamespace = Namespc;
11200  if (AddToKnown)
11201  KnownNamespaces[Namespc] = false;
11202 
11203  if (II) {
11204  PushOnScopeChains(Namespc, DeclRegionScope);
11205  } else {
11206  // Link the anonymous namespace into its parent.
11208  if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11209  TU->setAnonymousNamespace(Namespc);
11210  } else {
11211  cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11212  }
11213 
11214  CurContext->addDecl(Namespc);
11215 
11216  // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11217  // behaves as if it were replaced by
11218  // namespace unique { /* empty body */ }
11219  // using namespace unique;
11220  // namespace unique { namespace-body }
11221  // where all occurrences of 'unique' in a translation unit are
11222  // replaced by the same identifier and this identifier differs
11223  // from all other identifiers in the entire program.
11224 
11225  // We just create the namespace with an empty name and then add an
11226  // implicit using declaration, just like the standard suggests.
11227  //
11228  // CodeGen enforces the "universally unique" aspect by giving all
11229  // declarations semantically contained within an anonymous
11230  // namespace internal linkage.
11231 
11232  if (!PrevNS) {
11234  /* 'using' */ LBrace,
11235  /* 'namespace' */ SourceLocation(),
11236  /* qualifier */ NestedNameSpecifierLoc(),
11237  /* identifier */ SourceLocation(),
11238  Namespc,
11239  /* Ancestor */ Parent);
11240  UD->setImplicit();
11241  Parent->addDecl(UD);
11242  }
11243  }
11244 
11245  ActOnDocumentableDecl(Namespc);
11246 
11247  // Although we could have an invalid decl (i.e. the namespace name is a
11248  // redefinition), push it as current DeclContext and try to continue parsing.
11249  // FIXME: We should be able to push Namespc here, so that the each DeclContext
11250  // for the namespace has the declarations that showed up in that particular
11251  // namespace definition.
11252  PushDeclContext(NamespcScope, Namespc);
11253  return Namespc;
11254 }
11255 
11256 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11257 /// is a namespace alias, returns the namespace it points to.
11259  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11260  return AD->getNamespace();
11261  return dyn_cast_or_null<NamespaceDecl>(D);
11262 }
11263 
11264 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11265 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11267  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11268  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11269  Namespc->setRBraceLoc(RBrace);
11270  PopDeclContext();
11271  if (Namespc->hasAttr<VisibilityAttr>())
11272  PopPragmaVisibility(true, RBrace);
11273  // If this namespace contains an export-declaration, export it now.
11274  if (DeferredExportedNamespaces.erase(Namespc))
11276 }
11277 
11279  return cast_or_null<CXXRecordDecl>(
11281 }
11282 
11284  return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11285 }
11286 
11288  return cast_or_null<NamespaceDecl>(
11290 }
11291 
11294  if (auto Std = getStdNamespace()) {
11295  LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11297  if (!LookupQualifiedName(Result, Std) ||
11299  Result.getAsSingle<NamespaceDecl>()))
11300  Result.suppressDiagnostics();
11301  }
11302  }
11304 }
11305 
11306 namespace {
11307 
11308 enum UnsupportedSTLSelect {
11309  USS_InvalidMember,
11310  USS_MissingMember,
11311  USS_NonTrivial,
11312  USS_Other
11313 };
11314 
11315 struct InvalidSTLDiagnoser {
11316  Sema &S;
11317  SourceLocation Loc;
11318  QualType TyForDiags;
11319 
11320  QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11321  const VarDecl *VD = nullptr) {
11322  {
11323  auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11324  << TyForDiags << ((int)Sel);
11325  if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11326  assert(!Name.empty());
11327  D << Name;
11328  }
11329  }
11330  if (Sel == USS_InvalidMember) {
11331  S.Diag(VD->getLocation(), diag::note_var_declared_here)
11332  << VD << VD->getSourceRange();
11333  }
11334  return QualType();
11335  }
11336 };
11337 } // namespace
11338 
11340  SourceLocation Loc,
11341  ComparisonCategoryUsage Usage) {
11342  assert(getLangOpts().CPlusPlus &&
11343  "Looking for comparison category type outside of C++.");
11344 
11345  // Use an elaborated type for diagnostics which has a name containing the
11346  // prepended 'std' namespace but not any inline namespace names.
11347  auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11348  auto *NNS =
11350  return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11351  };
11352 
11353  // Check if we've already successfully checked the comparison category type
11354  // before. If so, skip checking it again.
11356  if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11357  // The only thing we need to check is that the type has a reachable
11358  // definition in the current context.
11359  if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11360  return QualType();
11361 
11362  return Info->getType();
11363  }
11364 
11365  // If lookup failed
11366  if (!Info) {
11367  std::string NameForDiags = "std::";
11369  Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11370  << NameForDiags << (int)Usage;
11371  return QualType();
11372  }
11373 
11374  assert(Info->Kind == Kind);
11375  assert(Info->Record);
11376 
11377  // Update the Record decl in case we encountered a forward declaration on our
11378  // first pass. FIXME: This is a bit of a hack.
11379  if (Info->Record->hasDefinition())
11380  Info->Record = Info->Record->getDefinition();
11381 
11382  if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11383  return QualType();
11384 
11385  InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11386 
11387  if (!Info->Record->isTriviallyCopyable())
11388  return UnsupportedSTLError(USS_NonTrivial);
11389 
11390  for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11391  CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11392  // Tolerate empty base classes.
11393  if (Base->isEmpty())
11394  continue;
11395  // Reject STL implementations which have at least one non-empty base.
11396  return UnsupportedSTLError();
11397  }
11398 
11399  // Check that the STL has implemented the types using a single integer field.
11400  // This expectation allows better codegen for builtin operators. We require:
11401  // (1) The class has exactly one field.
11402  // (2) The field is an integral or enumeration type.
11403  auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11404  if (std::distance(FIt, FEnd) != 1 ||
11405  !FIt->getType()->isIntegralOrEnumerationType()) {
11406  return UnsupportedSTLError();
11407  }
11408 
11409  // Build each of the require values and store them in Info.
11410  for (ComparisonCategoryResult CCR :
11412  StringRef MemName = ComparisonCategories::getResultString(CCR);
11413  ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11414 
11415  if (!ValInfo)
11416  return UnsupportedSTLError(USS_MissingMember, MemName);
11417 
11418  VarDecl *VD = ValInfo->VD;
11419  assert(VD && "should not be null!");
11420 
11421  // Attempt to diagnose reasons why the STL definition of this type
11422  // might be foobar, including it failing to be a constant expression.
11423  // TODO Handle more ways the lookup or result can be invalid.
11424  if (!VD->isStaticDataMember() ||
11426  return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11427 
11428  // Attempt to evaluate the var decl as a constant expression and extract
11429  // the value of its first field as a ICE. If this fails, the STL
11430  // implementation is not supported.
11431  if (!ValInfo->hasValidIntValue())
11432  return UnsupportedSTLError();
11433 
11434  MarkVariableReferenced(Loc, VD);
11435  }
11436 
11437  // We've successfully built the required types and expressions. Update
11438  // the cache and return the newly cached value.
11439  FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11440  return Info->getType();
11441 }
11442 
11443 /// Retrieve the special "std" namespace, which may require us to
11444 /// implicitly define the namespace.
11446  if (!StdNamespace) {
11447  // The "std" namespace has not yet been defined, so build one implicitly.
11450  /*Inline=*/false,
11452  &PP.getIdentifierTable().get("std"),
11453  /*PrevDecl=*/nullptr);
11454  getStdNamespace()->setImplicit(true);
11455  }
11456 
11457  return getStdNamespace();
11458 }
11459 
11461  assert(getLangOpts().CPlusPlus &&
11462  "Looking for std::initializer_list outside of C++.");
11463 
11464  // We're looking for implicit instantiations of
11465  // template <typename E> class std::initializer_list.
11466 
11467  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11468  return false;
11469 
11470  ClassTemplateDecl *Template = nullptr;
11471  const TemplateArgument *Arguments = nullptr;
11472 
11473  if (const RecordType *RT = Ty->getAs<RecordType>()) {
11474 
11476  dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11477  if (!Specialization)
11478  return false;
11479 
11480  Template = Specialization->getSpecializedTemplate();
11481  Arguments = Specialization->getTemplateArgs().data();
11482  } else if (const TemplateSpecializationType *TST =
11484  Template = dyn_cast_or_null<ClassTemplateDecl>(
11485  TST->getTemplateName().getAsTemplateDecl());
11486  Arguments = TST->getArgs();
11487  }
11488  if (!Template)
11489  return false;
11490 
11491  if (!StdInitializerList) {
11492  // Haven't recognized std::initializer_list yet, maybe this is it.
11493  CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11494  if (TemplateClass->getIdentifier() !=
11495  &PP.getIdentifierTable().get("initializer_list") ||
11496  !getStdNamespace()->InEnclosingNamespaceSetOf(
11497  TemplateClass->getDeclContext()))
11498  return false;
11499  // This is a template called std::initializer_list, but is it the right
11500  // template?
11501  TemplateParameterList *Params = Template->getTemplateParameters();
11502  if (Params->getMinRequiredArguments() != 1)
11503  return false;
11504  if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11505  return false;
11506 
11507  // It's the right template.
11508  StdInitializerList = Template;
11509  }
11510 
11512  return false;
11513 
11514  // This is an instance of std::initializer_list. Find the argument type.
11515  if (Element)
11516  *Element = Arguments[0].getAsType();
11517  return true;
11518 }
11519 
11522  if (!Std) {
11523  S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11524  return nullptr;
11525  }
11526 
11527  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11529  if (!S.LookupQualifiedName(Result, Std)) {
11530  S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11531  return nullptr;
11532  }
11533  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11534  if (!Template) {
11535  Result.suppressDiagnostics();
11536  // We found something weird. Complain about the first thing we found.
11537  NamedDecl *Found = *Result.begin();
11538  S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11539  return nullptr;
11540  }
11541 
11542  // We found some template called std::initializer_list. Now verify that it's
11543  // correct.
11544  TemplateParameterList *Params = Template->getTemplateParameters();
11545  if (Params->getMinRequiredArguments() != 1 ||
11546  !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11547  S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11548  return nullptr;
11549  }
11550 
11551  return Template;
11552 }
11553 
11555  if (!StdInitializerList) {
11557  if (!StdInitializerList)
11558  return QualType();
11559  }
11560 
11561  TemplateArgumentListInfo Args(Loc, Loc);
11564  Loc)));
11565  return Context.getCanonicalType(
11567 }
11568 
11570  // C++ [dcl.init.list]p2:
11571  // A constructor is an initializer-list constructor if its first parameter
11572  // is of type std::initializer_list<E> or reference to possibly cv-qualified
11573  // std::initializer_list<E> for some type E, and either there are no other
11574  // parameters or else all other parameters have default arguments.
11575  if (!Ctor->hasOneParamOrDefaultArgs())
11576  return false;
11577 
11578  QualType ArgType = Ctor->getParamDecl(0)->getType();
11579  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11580  ArgType = RT->getPointeeType().getUnqualifiedType();
11581 
11582  return isStdInitializerList(ArgType, nullptr);
11583 }
11584 
11585 /// Determine whether a using statement is in a context where it will be
11586 /// apply in all contexts.
11588  switch (CurContext->getDeclKind()) {
11589  case Decl::TranslationUnit:
11590  return true;
11591  case Decl::LinkageSpec:
11593  default:
11594  return false;
11595  }
11596 }
11597 
11598 namespace {
11599 
11600 // Callback to only accept typo corrections that are namespaces.
11601 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11602 public:
11603  bool ValidateCandidate(const TypoCorrection &candidate) override {
11604  if (NamedDecl *ND = candidate.getCorrectionDecl())
11605  return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11606  return false;
11607  }
11608 
11609  std::unique_ptr<CorrectionCandidateCallback> clone() override {
11610  return std::make_unique<NamespaceValidatorCCC>(*this);
11611  }
11612 };
11613 
11614 }
11615 
11617  CXXScopeSpec &SS,
11618  SourceLocation IdentLoc,
11619  IdentifierInfo *Ident) {
11620  R.clear();
11621  NamespaceValidatorCCC CCC{};
11622  if (TypoCorrection Corrected =
11623  S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11625  if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11626  std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11627  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11628  Ident->getName().equals(CorrectedStr);
11629  S.diagnoseTypo(Corrected,
11630  S.PDiag(diag::err_using_directive_member_suggest)
11631  << Ident << DC << DroppedSpecifier << SS.getRange(),
11632  S.PDiag(diag::note_namespace_defined_here));
11633  } else {
11634  S.diagnoseTypo(Corrected,
11635  S.PDiag(diag::err_using_directive_suggest) << Ident,
11636  S.PDiag(diag::note_namespace_defined_here));
11637  }
11638  R.addDecl(Corrected.getFoundDecl());
11639  return true;
11640  }
11641  return false;
11642 }
11643 
11645  SourceLocation NamespcLoc, CXXScopeSpec &SS,
11646  SourceLocation IdentLoc,
11647  IdentifierInfo *NamespcName,
11648  const ParsedAttributesView &AttrList) {
11649  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11650  assert(NamespcName && "Invalid NamespcName.");
11651  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11652 
11653  // This can only happen along a recovery path.
11654  while (S->isTemplateParamScope())
11655  S = S->getParent();
11656  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11657 
11658  UsingDirectiveDecl *UDir = nullptr;
11659  NestedNameSpecifier *Qualifier = nullptr;
11660  if (SS.isSet())
11661  Qualifier = SS.getScopeRep();
11662 
11663  // Lookup namespace name.
11664  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11665  LookupParsedName(R, S, &SS);
11666  if (R.isAmbiguous())
11667  return nullptr;
11668 
11669  if (R.empty()) {
11670  R.clear();
11671  // Allow "using namespace std;" or "using namespace ::std;" even if
11672  // "std" hasn't been defined yet, for GCC compatibility.
11673  if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11674  NamespcName->isStr("std")) {
11675  Diag(IdentLoc, diag::ext_using_undefined_std);
11677  R.resolveKind();
11678  }
11679  // Otherwise, attempt typo correction.
11680  else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11681  }
11682 
11683  if (!R.empty()) {
11684  NamedDecl *Named = R.getRepresentativeDecl();
11686  assert(NS && "expected namespace decl");
11687 
11688  // The use of a nested name specifier may trigger deprecation warnings.
11689  DiagnoseUseOfDecl(Named, IdentLoc);
11690 
11691  // C++ [namespace.udir]p1:
11692  // A using-directive specifies that the names in the nominated
11693  // namespace can be used in the scope in which the
11694  // using-directive appears after the using-directive. During
11695  // unqualified name lookup (3.4.1), the names appear as if they
11696  // were declared in the nearest enclosing namespace which
11697  // contains both the using-directive and the nominated
11698  // namespace. [Note: in this context, "contains" means "contains
11699  // directly or indirectly". ]
11700 
11701  // Find enclosing context containing both using-directive and
11702  // nominated namespace.
11703  DeclContext *CommonAncestor = NS;
11704  while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11705  CommonAncestor = CommonAncestor->getParent();
11706 
11707  UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11709  IdentLoc, Named, CommonAncestor);
11710 
11713  Diag(IdentLoc, diag::warn_using_directive_in_header);
11714  }
11715 
11716  PushUsingDirective(S, UDir);
11717  } else {
11718  Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11719  }
11720 
11721  if (UDir)
11722  ProcessDeclAttributeList(S, UDir, AttrList);
11723 
11724  return UDir;
11725 }
11726 
11728  // If the scope has an associated entity and the using directive is at
11729  // namespace or translation unit scope, add the UsingDirectiveDecl into
11730  // its lookup structure so qualified name lookup can find it.
11731  DeclContext *Ctx = S->getEntity();
11732  if (Ctx && !Ctx->isFunctionOrMethod())
11733  Ctx->addDecl(UDir);
11734  else
11735  // Otherwise, it is at block scope. The using-directives will affect lookup
11736  // only to the end of the scope.
11737  S->PushUsingDirective(UDir);
11738 }
11739 
11741  SourceLocation UsingLoc,
11742  SourceLocation TypenameLoc, CXXScopeSpec &SS,
11743  UnqualifiedId &Name,
11744  SourceLocation EllipsisLoc,
11745  const ParsedAttributesView &AttrList) {
11746  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11747 
11748  if (SS.isEmpty()) {
11749  Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11750  return nullptr;
11751  }
11752 
11753  switch (Name.getKind()) {
11759  break;
11760 
11763  // C++11 inheriting constructors.
11764  Diag(Name.getBeginLoc(),
11766  ? diag::warn_cxx98_compat_using_decl_constructor
11767  : diag::err_using_decl_constructor)
11768  << SS.getRange();
11769 
11770  if (getLangOpts().CPlusPlus11) break;
11771 
11772  return nullptr;
11773 
11775  Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11776  return nullptr;
11777 
11779  Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11780  << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11781  return nullptr;
11782 
11784  llvm_unreachable("cannot parse qualified deduction guide name");
11785  }
11786 
11787  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11788  DeclarationName TargetName = TargetNameInfo.getName();
11789  if (!TargetName)
11790  return nullptr;
11791 
11792  // Warn about access declarations.
11793  if (UsingLoc.isInvalid()) {
11794  Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11795  ? diag::err_access_decl
11796  : diag::warn_access_decl_deprecated)
11797  << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11798  }
11799 
11800  if (EllipsisLoc.isInvalid()) {
11803  return nullptr;
11804  } else {
11806  !TargetNameInfo.containsUnexpandedParameterPack()) {
11807  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11808  << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11809  EllipsisLoc = SourceLocation();
11810  }
11811  }
11812 
11813  NamedDecl *UD =
11814  BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11815  SS, TargetNameInfo, EllipsisLoc, AttrList,
11816  /*IsInstantiation*/ false,
11817  AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11818  if (UD)
11819  PushOnScopeChains(UD, S, /*AddToContext*/ false);
11820 
11821  return UD;
11822 }
11823 
11825  SourceLocation UsingLoc,
11826  SourceLocation EnumLoc,
11827  const DeclSpec &DS) {
11828  switch (DS.getTypeSpecType()) {
11829  case DeclSpec::TST_error:
11830  // This will already have been diagnosed
11831  return nullptr;
11832 
11833  case DeclSpec::TST_enum:
11834  break;
11835 
11837  Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11838  return nullptr;
11839 
11840  default:
11841  llvm_unreachable("unexpected DeclSpec type");
11842  }
11843 
11844  // As with enum-decls, we ignore attributes for now.
11845  auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11846  if (auto *Def = Enum->getDefinition())
11847  Enum = Def;
11848 
11849  auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11850  DS.getTypeSpecTypeNameLoc(), Enum);
11851  if (UD)
11852  PushOnScopeChains(UD, S, /*AddToContext*/ false);
11853 
11854  return UD;
11855 }
11856 
11857 /// Determine whether a using declaration considers the given
11858 /// declarations as "equivalent", e.g., if they are redeclarations of
11859 /// the same entity or are both typedefs of the same type.
11860 static bool
11862  if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11863  return true;
11864 
11865  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11866  if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11867  return Context.hasSameType(TD1->getUnderlyingType(),
11868  TD2->getUnderlyingType());
11869 
11870  // Two using_if_exists using-declarations are equivalent if both are
11871  // unresolved.
11872  if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11873  isa<UnresolvedUsingIfExistsDecl>(D2))
11874  return true;
11875 
11876  return false;
11877 }
11878 
11879 
11880 /// Determines whether to create a using shadow decl for a particular
11881 /// decl, given the set of decls existing prior to this using lookup.
11883  const LookupResult &Previous,
11884  UsingShadowDecl *&PrevShadow) {
11885  // Diagnose finding a decl which is not from a base class of the
11886  // current class. We do this now because there are cases where this
11887  // function will silently decide not to build a shadow decl, which
11888  // will pre-empt further diagnostics.
11889  //
11890  // We don't need to do this in C++11 because we do the check once on
11891  // the qualifier.
11892  //
11893  // FIXME: diagnose the following if we care enough:
11894  // struct A { int foo; };
11895  // struct B : A { using A::foo; };
11896  // template <class T> struct C : A {};
11897  // template <class T> struct D : C<T> { using B::foo; } // <---
11898  // This is invalid (during instantiation) in C++03 because B::foo
11899  // resolves to the using decl in B, which is not a base class of D<T>.
11900  // We can't diagnose it immediately because C<T> is an unknown
11901  // specialization. The UsingShadowDecl in D<T> then points directly
11902  // to A::foo, which will look well-formed when we instantiate.
11903  // The right solution is to not collapse the shadow-decl chain.
11905  if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11906  DeclContext *OrigDC = Orig->getDeclContext();
11907 
11908  // Handle enums and anonymous structs.
11909  if (isa<EnumDecl>(OrigDC))
11910  OrigDC = OrigDC->getParent();
11911  CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11912  while (OrigRec->isAnonymousStructOrUnion())
11913  OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11914 
11915  if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11916  if (OrigDC == CurContext) {
11917  Diag(Using->getLocation(),
11918  diag::err_using_decl_nested_name_specifier_is_current_class)
11919  << Using->getQualifierLoc().getSourceRange();
11920  Diag(Orig->getLocation(), diag::note_using_decl_target);
11921  Using->setInvalidDecl();
11922  return true;
11923  }
11924 
11925  Diag(Using->getQualifierLoc().getBeginLoc(),
11926  diag::err_using_decl_nested_name_specifier_is_not_base_class)
11927  << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11928  << Using->getQualifierLoc().getSourceRange();
11929  Diag(Orig->getLocation(), diag::note_using_decl_target);
11930  Using->setInvalidDecl();
11931  return true;
11932  }
11933  }
11934 
11935  if (Previous.empty()) return false;
11936 
11937  NamedDecl *Target = Orig;
11938  if (isa<UsingShadowDecl>(Target))
11939  Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11940 
11941  // If the target happens to be one of the previous declarations, we
11942  // don't have a conflict.
11943  //
11944  // FIXME: but we might be increasing its access, in which case we
11945  // should redeclare it.
11946  NamedDecl *NonTag = nullptr, *Tag = nullptr;
11947  bool FoundEquivalentDecl = false;
11948  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11949  I != E; ++I) {
11950  NamedDecl *D = (*I)->getUnderlyingDecl();
11951  // We can have UsingDecls in our Previous results because we use the same
11952  // LookupResult for checking whether the UsingDecl itself is a valid
11953  // redeclaration.
11954  if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11955  continue;
11956 
11957  if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11958  // C++ [class.mem]p19:
11959  // If T is the name of a class, then [every named member other than
11960  // a non-static data member] shall have a name different from T
11961  if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11962  !isa<IndirectFieldDecl>(Target) &&
11963  !isa<UnresolvedUsingValueDecl>(Target) &&
11965  CurContext,
11966  DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11967  return true;
11968  }
11969 
11971  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11972  PrevShadow = Shadow;
11973  FoundEquivalentDecl = true;
11975  // We don't conflict with an existing using shadow decl of an equivalent
11976  // declaration, but we're not a redeclaration of it.
11977  FoundEquivalentDecl = true;
11978  }
11979 
11980  if (isVisible(D))
11981  (isa<TagDecl>(D) ? Tag : NonTag) = D;
11982  }
11983 
11984  if (FoundEquivalentDecl)
11985  return false;
11986 
11987  // Always emit a diagnostic for a mismatch between an unresolved
11988  // using_if_exists and a resolved using declaration in either direction.
11989  if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11990  (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11991  if (!NonTag && !Tag)
11992  return false;
11993  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11994  Diag(Target->getLocation(), diag::note_using_decl_target);
11995  Diag((NonTag ? NonTag : Tag)->getLocation(),
11996  diag::note_using_decl_conflict);
11997  BUD->setInvalidDecl();
11998  return true;
11999  }
12000 
12001  if (FunctionDecl *FD = Target->getAsFunction()) {
12002  NamedDecl *OldDecl = nullptr;
12003  switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12004  /*IsForUsingDecl*/ true)) {
12005  case Ovl_Overload:
12006  return false;
12007 
12008  case Ovl_NonFunction:
12009  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12010  break;
12011 
12012  // We found a decl with the exact signature.
12013  case Ovl_Match:
12014  // If we're in a record, we want to hide the target, so we
12015  // return true (without a diagnostic) to tell the caller not to
12016  // build a shadow decl.
12017  if (CurContext->isRecord())
12018  return true;
12019 
12020  // If we're not in a record, this is an error.
12021  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12022  break;
12023  }
12024 
12025  Diag(Target->getLocation(), diag::note_using_decl_target);
12026  Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12027  BUD->setInvalidDecl();
12028  return true;
12029  }
12030 
12031  // Target is not a function.
12032 
12033  if (isa<TagDecl>(Target)) {
12034  // No conflict between a tag and a non-tag.
12035  if (!Tag) return false;
12036 
12037  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12038  Diag(Target->getLocation(), diag::note_using_decl_target);
12039  Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12040  BUD->setInvalidDecl();
12041  return true;
12042  }
12043 
12044  // No conflict between a tag and a non-tag.
12045  if (!NonTag) return false;
12046 
12047  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12048  Diag(Target->getLocation(), diag::note_using_decl_target);
12049  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12050  BUD->setInvalidDecl();
12051  return true;
12052 }
12053 
12054 /// Determine whether a direct base class is a virtual base class.
12056  if (!Derived->getNumVBases())
12057  return false;
12058  for (auto &B : Derived->bases())
12059  if (B.getType()->getAsCXXRecordDecl() == Base)
12060  return B.isVirtual();
12061  llvm_unreachable("not a direct base class");
12062 }
12063 
12064 /// Builds a shadow declaration corresponding to a 'using' declaration.
12066  NamedDecl *Orig,
12067  UsingShadowDecl *PrevDecl) {
12068  // If we resolved to another shadow declaration, just coalesce them.
12069  NamedDecl *Target = Orig;
12070  if (isa<UsingShadowDecl>(Target)) {
12071  Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12072  assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12073  }
12074 
12075  NamedDecl *NonTemplateTarget = Target;
12076  if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12077  NonTemplateTarget = TargetTD->getTemplatedDecl();
12078 
12079  UsingShadowDecl *Shadow;
12080  if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12081  UsingDecl *Using = cast<UsingDecl>(BUD);
12082  bool IsVirtualBase =
12083  isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12084  Using->getQualifier()->getAsRecordDecl());
12086  Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12087  } else {
12089  Target->getDeclName(), BUD, Target);
12090  }
12091  BUD->addShadowDecl(Shadow);
12092 
12093  Shadow->setAccess(BUD->getAccess());
12094  if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12095  Shadow->setInvalidDecl();
12096 
12097  Shadow->setPreviousDecl(PrevDecl);
12098 
12099  if (S)
12100  PushOnScopeChains(Shadow, S);
12101  else
12102  CurContext->addDecl(Shadow);
12103 
12104 
12105  return Shadow;
12106 }
12107 
12108 /// Hides a using shadow declaration. This is required by the current
12109 /// using-decl implementation when a resolvable using declaration in a
12110 /// class is followed by a declaration which would hide or override
12111 /// one or more of the using decl's targets; for example:
12112 ///
12113 /// struct Base { void foo(int); };
12114 /// struct Derived : Base {
12115 /// using Base::foo;
12116 /// void foo(int);
12117 /// };
12118 ///
12119 /// The governing language is C++03 [namespace.udecl]p12:
12120 ///
12121 /// When a using-declaration brings names from a base class into a
12122 /// derived class scope, member functions in the derived class
12123 /// override and/or hide member functions with the same name and
12124 /// parameter types in a base class (rather than conflicting).
12125 ///
12126 /// There are two ways to implement this:
12127 /// (1) optimistically create shadow decls when they're not hidden
12128 /// by existing declarations, or
12129 /// (2) don't create any shadow decls (or at least don't make them
12130 /// visible) until we've fully parsed/instantiated the class.
12131 /// The problem with (1) is that we might have to retroactively remove
12132 /// a shadow decl, which requires several O(n) operations because the
12133 /// decl structures are (very reasonably) not designed for removal.
12134 /// (2) avoids this but is very fiddly and phase-dependent.
12136  if (Shadow->getDeclName().getNameKind() ==
12138  cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12139 
12140  // Remove it from the DeclContext...
12141  Shadow->getDeclContext()->removeDecl(Shadow);
12142 
12143  // ...and the scope, if applicable...
12144  if (S) {
12145  S->RemoveDecl(Shadow);
12146  IdResolver.RemoveDecl(Shadow);
12147  }
12148 
12149  // ...and the using decl.
12150  Shadow->getIntroducer()->removeShadowDecl(Shadow);
12151 
12152  // TODO: complain somehow if Shadow was used. It shouldn't
12153  // be possible for this to happen, because...?
12154 }
12155 
12156 /// Find the base specifier for a base class with the given type.
12158  QualType DesiredBase,
12159  bool &AnyDependentBases) {
12160  // Check whether the named type is a direct base class.
12161  CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12162  .getUnqualifiedType();
12163  for (auto &Base : Derived->bases()) {
12164  CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12165  if (CanonicalDesiredBase == BaseType)
12166  return &Base;
12167  if (BaseType->isDependentType())
12168  AnyDependentBases = true;
12169  }
12170  return nullptr;
12171 }
12172 
12173 namespace {
12174 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12175 public:
12176  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12177  NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12178  : HasTypenameKeyword(HasTypenameKeyword),
12179  IsInstantiation(IsInstantiation), OldNNS(NNS),
12180  RequireMemberOf(RequireMemberOf) {}
12181 
12182  bool ValidateCandidate(const TypoCorrection &Candidate) override {
12183  NamedDecl *ND = Candidate.getCorrectionDecl();
12184 
12185  // Keywords are not valid here.
12186  if (!ND || isa<NamespaceDecl>(ND))
12187  return false;
12188 
12189  // Completely unqualified names are invalid for a 'using' declaration.
12190  if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12191  return false;
12192 
12193  // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12194  // reject.
12195 
12196  if (RequireMemberOf) {
12197  auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12198  if (FoundRecord && FoundRecord->isInjectedClassName()) {
12199  // No-one ever wants a using-declaration to name an injected-class-name
12200  // of a base class, unless they're declaring an inheriting constructor.
12201  ASTContext &Ctx = ND->getASTContext();
12202  if (!Ctx.getLangOpts().CPlusPlus11)
12203  return false;
12204  QualType FoundType = Ctx.getRecordType(FoundRecord);
12205 
12206  // Check that the injected-class-name is named as a member of its own
12207  // type; we don't want to suggest 'using Derived::Base;', since that
12208  // means something else.
12210  Candidate.WillReplaceSpecifier()
12211  ? Candidate.getCorrectionSpecifier()
12212  : OldNNS;
12213  if (!Specifier->getAsType() ||
12214  !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12215  return false;
12216 
12217  // Check that this inheriting constructor declaration actually names a
12218  // direct base class of the current class.
12219  bool AnyDependentBases = false;
12220  if (!findDirectBaseWithType(RequireMemberOf,
12221  Ctx.getRecordType(FoundRecord),
12222  AnyDependentBases) &&
12223  !AnyDependentBases)
12224  return false;
12225  } else {
12226  auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12227  if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12228  return false;
12229 
12230  // FIXME: Check that the base class member is accessible?
12231  }
12232  } else {
12233  auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12234  if (FoundRecord && FoundRecord->isInjectedClassName())
12235  return false;
12236  }
12237 
12238  if (isa<TypeDecl>(ND))
12239  return HasTypenameKeyword || !IsInstantiation;
12240 
12241  return !HasTypenameKeyword;
12242  }
12243 
12244  std::unique_ptr<CorrectionCandidateCallback> clone() override {
12245  return std::make_unique<UsingValidatorCCC>(*this);
12246  }
12247 
12248 private:
12249  bool HasTypenameKeyword;
12250  bool IsInstantiation;
12251  NestedNameSpecifier *OldNNS;
12252  CXXRecordDecl *RequireMemberOf;
12253 };
12254 } // end anonymous namespace
12255 
12256 /// Remove decls we can't actually see from a lookup being used to declare
12257 /// shadow using decls.
12258 ///
12259 /// \param S - The scope of the potential shadow decl
12260 /// \param Previous - The lookup of a potential shadow decl's name.
12262  // It is really dumb that we have to do this.
12263  LookupResult::Filter F = Previous.makeFilter();
12264  while (F.hasNext()) {
12265  NamedDecl *D = F.next();
12266  if (!isDeclInScope(D, CurContext, S))
12267  F.erase();
12268  // If we found a local extern declaration that's not ordinarily visible,
12269  // and this declaration is being added to a non-block scope, ignore it.
12270  // We're only checking for scope conflicts here, not also for violations
12271  // of the linkage rules.
12272  else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12274  F.erase();
12275  }
12276  F.done();
12277 }
12278 
12279 /// Builds a using declaration.
12280 ///
12281 /// \param IsInstantiation - Whether this call arises from an
12282 /// instantiation of an unresolved using declaration. We treat
12283 /// the lookup differently for these declarations.
12285  Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12286  bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12287  DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12288  const ParsedAttributesView &AttrList, bool IsInstantiation,
12289  bool IsUsingIfExists) {
12290  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12291  SourceLocation IdentLoc = NameInfo.getLoc();
12292  assert(IdentLoc.isValid() && "Invalid TargetName location.");
12293 
12294  // FIXME: We ignore attributes for now.
12295 
12296  // For an inheriting constructor declaration, the name of the using
12297  // declaration is the name of a constructor in this class, not in the
12298  // base class.
12299  DeclarationNameInfo UsingName = NameInfo;
12301  if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12304 
12305  // Do the redeclaration lookup in the current scope.
12306  LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12308  Previous.setHideTags(false);
12309  if (S) {
12310  LookupName(Previous, S);
12311 
12313  } else {
12314  assert(IsInstantiation && "no scope in non-instantiation");
12315  if (CurContext->isRecord())
12317  else {
12318  // No redeclaration check is needed here; in non-member contexts we
12319  // diagnosed all possible conflicts with other using-declarations when
12320  // building the template:
12321  //
12322  // For a dependent non-type using declaration, the only valid case is
12323  // if we instantiate to a single enumerator. We check for conflicts
12324  // between shadow declarations we introduce, and we check in the template
12325  // definition for conflicts between a non-type using declaration and any
12326  // other declaration, which together covers all cases.
12327  //
12328  // A dependent typename using declaration will never successfully
12329  // instantiate, since it will always name a class member, so we reject
12330  // that in the template definition.
12331  }
12332  }
12333 
12334  // Check for invalid redeclarations.
12335  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12336  SS, IdentLoc, Previous))
12337  return nullptr;
12338 
12339  // 'using_if_exists' doesn't make sense on an inherited constructor.
12340  if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12342  Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12343  return nullptr;
12344  }
12345 
12346  DeclContext *LookupContext = computeDeclContext(SS);
12348  if (!LookupContext || EllipsisLoc.isValid()) {
12349  NamedDecl *D;
12350  // Dependent scope, or an unexpanded pack
12351  if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12352  SS, NameInfo, IdentLoc))
12353  return nullptr;
12354 
12355  if (HasTypenameKeyword) {
12356  // FIXME: not all declaration name kinds are legal here
12358  UsingLoc, TypenameLoc,
12359  QualifierLoc,
12360  IdentLoc, NameInfo.getName(),
12361  EllipsisLoc);
12362  } else {
12364  QualifierLoc, NameInfo, EllipsisLoc);
12365  }
12366  D->setAccess(AS);
12367  CurContext->addDecl(D);
12368  ProcessDeclAttributeList(S, D, AttrList);
12369  return D;
12370  }
12371 
12372  auto Build = [&](bool Invalid) {
12373  UsingDecl *UD =
12374  UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12375  UsingName, HasTypenameKeyword);
12376  UD->setAccess(AS);
12377  CurContext->addDecl(UD);
12378  ProcessDeclAttributeList(S, UD, AttrList);
12379  UD->setInvalidDecl(Invalid);
12380  return UD;
12381  };
12382  auto BuildInvalid = [&]{ return Build(true); };
12383  auto BuildValid = [&]{ return Build(false); };
12384 
12385  if (RequireCompleteDeclContext(SS, LookupContext))
12386  return BuildInvalid();
12387 
12388  // Look up the target name.
12389  LookupResult R(*this, NameInfo, LookupOrdinaryName);
12390 
12391  // Unlike most lookups, we don't always want to hide tag
12392  // declarations: tag names are visible through the using declaration
12393  // even if hidden by ordinary names, *except* in a dependent context
12394  // where they may be used by two-phase lookup.
12395  if (!IsInstantiation)
12396  R.setHideTags(false);
12397 
12398  // For the purposes of this lookup, we have a base object type
12399  // equal to that of the current context.
12400  if (CurContext->isRecord()) {
12402  Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12403  }
12404 
12405  LookupQualifiedName(R, LookupContext);
12406 
12407  // Validate the context, now we have a lookup
12408  if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12409  IdentLoc, &R))
12410  return nullptr;
12411 
12412  if (R.empty() && IsUsingIfExists)
12414  UsingName.getName()),
12415  AS_public);
12416 
12417  // Try to correct typos if possible. If constructor name lookup finds no
12418  // results, that means the named class has no explicit constructors, and we
12419  // suppressed declaring implicit ones (probably because it's dependent or
12420  // invalid).
12421  if (R.empty() &&
12423  // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12424  // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12425  // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12426  auto *II = NameInfo.getName().getAsIdentifierInfo();
12427  if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12429  isa<TranslationUnitDecl>(LookupContext) &&
12430  getSourceManager().isInSystemHeader(UsingLoc))
12431  return nullptr;
12432  UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12433  dyn_cast<CXXRecordDecl>(CurContext));
12434  if (TypoCorrection Corrected =
12435  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12436  CTK_ErrorRecovery)) {
12437  // We reject candidates where DroppedSpecifier == true, hence the
12438  // literal '0' below.
12439  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12440  << NameInfo.getName() << LookupContext << 0
12441  << SS.getRange());
12442 
12443  // If we picked a correction with no attached Decl we can't do anything
12444  // useful with it, bail out.
12445  NamedDecl *ND = Corrected.getCorrectionDecl();
12446  if (!ND)
12447  return BuildInvalid();
12448 
12449  // If we corrected to an inheriting constructor, handle it as one.
12450  auto *RD = dyn_cast<CXXRecordDecl>(ND);
12451  if (RD && RD->isInjectedClassName()) {
12452  // The parent of the injected class name is the class itself.
12453  RD = cast<CXXRecordDecl>(RD->getParent());
12454 
12455  // Fix up the information we'll use to build the using declaration.
12456  if (Corrected.WillReplaceSpecifier()) {
12458  Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12459  QualifierLoc.getSourceRange());
12460  QualifierLoc = Builder.getWithLocInContext(Context);
12461  }
12462 
12463  // In this case, the name we introduce is the name of a derived class
12464  // constructor.
12465  auto *CurClass = cast<CXXRecordDecl>(CurContext);
12468  UsingName.setNamedTypeInfo(nullptr);
12469  for (auto *Ctor : LookupConstructors(RD))
12470  R.addDecl(Ctor);
12471  R.resolveKind();
12472  } else {
12473  // FIXME: Pick up all the declarations if we found an overloaded
12474  // function.
12475  UsingName.setName(ND->getDeclName());
12476  R.addDecl(ND);
12477  }
12478  } else {
12479  Diag(IdentLoc, diag::err_no_member)
12480  << NameInfo.getName() << LookupContext << SS.getRange();
12481  return BuildInvalid();
12482  }
12483  }
12484 
12485  if (R.isAmbiguous())
12486  return BuildInvalid();
12487 
12488  if (HasTypenameKeyword) {
12489  // If we asked for a typename and got a non-type decl, error out.
12490  if (!R.getAsSingle<TypeDecl>() &&
12492  Diag(IdentLoc, diag::err_using_typename_non_type);
12493  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12494  Diag((*I)->getUnderlyingDecl()->getLocation(),
12495  diag::note_using_decl_target);
12496  return BuildInvalid();
12497  }
12498  } else {
12499  // If we asked for a non-typename and we got a type, error out,
12500  // but only if this is an instantiation of an unresolved using
12501  // decl. Otherwise just silently find the type name.
12502  if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12503  Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12504  Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12505  return BuildInvalid();
12506  }
12507  }
12508 
12509  // C++14 [namespace.udecl]p6:
12510  // A using-declaration shall not name a namespace.
12511  if (R.getAsSingle<NamespaceDecl>()) {
12512  Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12513  << SS.getRange();
12514  return BuildInvalid();
12515  }
12516 
12517  UsingDecl *UD = BuildValid();
12518 
12519  // Some additional rules apply to inheriting constructors.
12520  if (UsingName.getName().getNameKind() ==
12522  // Suppress access diagnostics; the access check is instead performed at the
12523  // point of use for an inheriting constructor.
12524  R.suppressDiagnostics();
12526  return UD;
12527  }
12528 
12529  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12530  UsingShadowDecl *PrevDecl = nullptr;
12531  if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12532  BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12533  }
12534 
12535  return UD;
12536 }
12537 
12539  SourceLocation UsingLoc,
12540  SourceLocation EnumLoc,
12541  SourceLocation NameLoc,
12542  EnumDecl *ED) {
12543  bool Invalid = false;
12544 
12545  if (CurContext->getRedeclContext()->isRecord()) {
12546  /// In class scope, check if this is a duplicate, for better a diagnostic.
12547  DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12548  LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12550 
12551  LookupName(Previous, S);
12552 
12553  for (NamedDecl *D : Previous)
12554  if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12555  if (UED->getEnumDecl() == ED) {
12556  Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12557  << SourceRange(EnumLoc, NameLoc);
12558  Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12559  Invalid = true;
12560  break;
12561  }
12562  }
12563 
12564  if (RequireCompleteEnumDecl(ED, NameLoc))
12565  Invalid = true;
12566 
12568  EnumLoc, NameLoc, ED);
12569  UD->setAccess(AS);
12570  CurContext->addDecl(UD);
12571 
12572  if (Invalid) {
12573  UD->setInvalidDecl();
12574  return UD;
12575  }
12576 
12577  // Create the shadow decls for each enumerator
12578  for (EnumConstantDecl *EC : ED->enumerators()) {
12579  UsingShadowDecl *PrevDecl = nullptr;
12580  DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12583  LookupName(Previous, S);
12585 
12586  if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12587  BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12588  }
12589 
12590  return UD;
12591 }
12592 
12594  ArrayRef<NamedDecl *> Expansions) {
12595  assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12596  isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12597  isa<UsingPackDecl>(InstantiatedFrom));
12598 
12599  auto *UPD =
12600  UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12601  UPD->setAccess(InstantiatedFrom->getAccess());
12602  CurContext->addDecl(UPD);
12603  return UPD;
12604 }
12605 
12606 /// Additional checks for a using declaration referring to a constructor name.
12608  assert(!UD->hasTypename() && "expecting a constructor name");
12609 
12610  const Type *SourceType = UD->getQualifier()->getAsType();
12611  assert(SourceType &&
12612  "Using decl naming constructor doesn't have type in scope spec.");
12613  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12614 
12615  // Check whether the named type is a direct base class.
12616  bool AnyDependentBases = false;
12617  auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12618  AnyDependentBases);
12619  if (!Base && !AnyDependentBases) {
12620  Diag(UD->getUsingLoc(),
12621  diag::err_using_decl_constructor_not_in_direct_base)
12622  << UD->getNameInfo().getSourceRange()
12623  << QualType(SourceType, 0) << TargetClass;
12624  UD->setInvalidDecl();
12625  return true;
12626  }
12627 
12628  if (Base)
12629  Base->setInheritConstructors();
12630 
12631  return false;
12632 }
12633 
12634 /// Checks that the given using declaration is not an invalid
12635 /// redeclaration. Note that this is checking only for the using decl
12636 /// itself, not for any ill-formedness among the UsingShadowDecls.
12638  bool HasTypenameKeyword,
12639  const CXXScopeSpec &SS,
12640  SourceLocation NameLoc,
12641  const LookupResult &Prev) {
12642  NestedNameSpecifier *Qual = SS.getScopeRep();
12643 
12644  // C++03 [namespace.udecl]p8:
12645  // C++0x [namespace.udecl]p10:
12646  // A using-declaration is a declaration and can therefore be used
12647  // repeatedly where (and only where) multiple declarations are
12648  // allowed.
12649  //
12650  // That's in non-member contexts.
12651  if (!CurContext->getRedeclContext()->isRecord()) {
12652  // A dependent qualifier outside a class can only ever resolve to an
12653  // enumeration type. Therefore it conflicts with any other non-type
12654  // declaration in the same scope.
12655  // FIXME: How should we check for dependent type-type conflicts at block
12656  // scope?
12657  if (Qual->isDependent() && !HasTypenameKeyword) {
12658  for (auto *D : Prev) {
12659  if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12660  bool OldCouldBeEnumerator =
12661  isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12662  Diag(NameLoc,
12663  OldCouldBeEnumerator ? diag::err_redefinition
12664  : diag::err_redefinition_different_kind)
12665  << Prev.getLookupName();
12666  Diag(D->getLocation(), diag::note_previous_definition);
12667  return true;
12668  }
12669  }
12670  }
12671  return false;
12672  }
12673 
12674  const NestedNameSpecifier *CNNS =
12676  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12677  NamedDecl *D = *I;
12678 
12679  bool DTypename;
12680  NestedNameSpecifier *DQual;
12681  if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12682  DTypename = UD->hasTypename();
12683  DQual = UD->getQualifier();
12684  } else if (UnresolvedUsingValueDecl *UD
12685  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12686  DTypename = false;
12687  DQual = UD->getQualifier();
12688  } else if (UnresolvedUsingTypenameDecl *UD
12689  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12690  DTypename = true;
12691  DQual = UD->getQualifier();
12692  } else continue;
12693 
12694  // using decls differ if one says 'typename' and the other doesn't.
12695  // FIXME: non-dependent using decls?
12696  if (HasTypenameKeyword != DTypename) continue;
12697 
12698  // using decls differ if they name different scopes (but note that
12699  // template instantiation can cause this check to trigger when it
12700  // didn't before instantiation).
12701  if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12702  continue;
12703 
12704  Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12705  Diag(D->getLocation(), diag::note_using_decl) << 1;
12706  return true;
12707  }
12708 
12709  return false;
12710 }
12711 
12712 /// Checks that the given nested-name qualifier used in a using decl
12713 /// in the current context is appropriately related to the current
12714 /// scope. If an error is found, diagnoses it and returns true.
12715 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12716 /// result of that lookup. UD is likewise nullptr, except when we have an
12717 /// already-populated UsingDecl whose shadow decls contain the same information
12718 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12719 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12720  const CXXScopeSpec &SS,
12721  const DeclarationNameInfo &NameInfo,
12722  SourceLocation NameLoc,
12723  const LookupResult *R, const UsingDecl *UD) {
12724  DeclContext *NamedContext = computeDeclContext(SS);
12725  assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12726  "resolvable context must have exactly one set of decls");
12727 
12728  // C++ 20 permits using an enumerator that does not have a class-hierarchy
12729  // relationship.
12730  bool Cxx20Enumerator = false;
12731  if (NamedContext) {
12732  EnumConstantDecl *EC = nullptr;
12733  if (R)
12734  EC = R->getAsSingle<EnumConstantDecl>();
12735  else if (UD && UD->shadow_size() == 1)
12736  EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12737  if (EC)
12738  Cxx20Enumerator = getLangOpts().CPlusPlus20;
12739 
12740  if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12741  // C++14 [namespace.udecl]p7:
12742  // A using-declaration shall not name a scoped enumerator.
12743  // C++20 p1099 permits enumerators.
12744  if (EC && R && ED->isScoped())
12745  Diag(SS.getBeginLoc(),
12747  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12748  : diag::ext_using_decl_scoped_enumerator)
12749  << SS.getRange();
12750 
12751  // We want to consider the scope of the enumerator
12752  NamedContext = ED->getDeclContext();
12753  }
12754  }
12755 
12756  if (!CurContext->isRecord()) {
12757  // C++03 [namespace.udecl]p3:
12758  // C++0x [namespace.udecl]p8:
12759  // A using-declaration for a class member shall be a member-declaration.
12760  // C++20 [namespace.udecl]p7
12761  // ... other than an enumerator ...
12762 
12763  // If we weren't able to compute a valid scope, it might validly be a
12764  // dependent class or enumeration scope. If we have a 'typename' keyword,
12765  // the scope must resolve to a class type.
12766  if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12767  : !HasTypename)
12768  return false; // OK
12769 
12770  Diag(NameLoc,
12771  Cxx20Enumerator
12772  ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12773  : diag::err_using_decl_can_not_refer_to_class_member)
12774  << SS.getRange();
12775 
12776  if (Cxx20Enumerator)
12777  return false; // OK
12778 
12779  auto *RD = NamedContext
12780  ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12781  : nullptr;
12782  if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12783  // See if there's a helpful fixit
12784 
12785  if (!R) {
12786  // We will have already diagnosed the problem on the template
12787  // definition, Maybe we should do so again?
12788  } else if (R->getAsSingle<TypeDecl>()) {
12789  if (getLangOpts().CPlusPlus11) {
12790  // Convert 'using X::Y;' to 'using Y = X::Y;'.
12791  Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12792  << 0 // alias declaration
12794  NameInfo.getName().getAsString() +
12795  " = ");
12796  } else {
12797  // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12798  SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12799  Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12800  << 1 // typedef declaration
12801  << FixItHint::CreateReplacement(UsingLoc, "typedef")
12803  InsertLoc, " " + NameInfo.getName().getAsString());
12804  }
12805  } else if (R->getAsSingle<VarDecl>()) {
12806  // Don't provide a fixit outside C++11 mode; we don't want to suggest
12807  // repeating the type of the static data member here.
12808  FixItHint FixIt;
12809  if (getLangOpts().CPlusPlus11) {
12810  // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12812  UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12813  }
12814 
12815  Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12816  << 2 // reference declaration
12817  << FixIt;
12818  } else if (R->getAsSingle<EnumConstantDecl>()) {
12819  // Don't provide a fixit outside C++11 mode; we don't want to suggest
12820  // repeating the type of the enumeration here, and we can't do so if
12821  // the type is anonymous.
12822  FixItHint FixIt;
12823  if (getLangOpts().CPlusPlus11) {
12824  // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12826  UsingLoc,
12827  "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12828  }
12829 
12830  Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12831  << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12832  << FixIt;
12833  }
12834  }
12835 
12836  return true; // Fail
12837  }
12838 
12839  // If the named context is dependent, we can't decide much.
12840  if (!NamedContext) {
12841  // FIXME: in C++0x, we can diagnose if we can prove that the
12842  // nested-name-specifier does not refer to a base class, which is
12843  // still possible in some cases.
12844 
12845  // Otherwise we have to conservatively report that things might be
12846  // okay.
12847  return false;
12848  }
12849 
12850  // The current scope is a record.
12851  if (!NamedContext->isRecord()) {
12852  // Ideally this would point at the last name in the specifier,
12853  // but we don't have that level of source info.
12854  Diag(SS.getBeginLoc(),
12855  Cxx20Enumerator
12856  ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12857  : diag::err_using_decl_nested_name_specifier_is_not_class)
12858  << SS.getScopeRep() << SS.getRange();
12859 
12860  if (Cxx20Enumerator)
12861  return false; // OK
12862 
12863  return true;
12864  }
12865 
12866  if (!NamedContext->isDependentContext() &&
12867  RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12868  return true;
12869 
12870  if (getLangOpts().CPlusPlus11) {
12871  // C++11 [namespace.udecl]p3:
12872  // In a using-declaration used as a member-declaration, the
12873  // nested-name-specifier shall name a base class of the class
12874  // being defined.
12875 
12876  if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12877  cast<CXXRecordDecl>(NamedContext))) {
12878 
12879  if (Cxx20Enumerator) {
12880  Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12881  << SS.getRange();
12882  return false;
12883  }
12884 
12885  if (CurContext == NamedContext) {
12886  Diag(SS.getBeginLoc(),
12887  diag::err_using_decl_nested_name_specifier_is_current_class)
12888  << SS.getRange();
12889  return !getLangOpts().CPlusPlus20;
12890  }
12891 
12892  if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12893  Diag(SS.getBeginLoc(),
12894  diag::err_using_decl_nested_name_specifier_is_not_base_class)
12895  << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12896  << SS.getRange();
12897  }
12898  return true;
12899  }
12900 
12901  return false;
12902  }
12903 
12904  // C++03 [namespace.udecl]p4:
12905  // A using-declaration used as a member-declaration shall refer
12906  // to a member of a base class of the class being defined [etc.].
12907 
12908  // Salient point: SS doesn't have to name a base class as long as
12909  // lookup only finds members from base classes. Therefore we can
12910  // diagnose here only if we can prove that that can't happen,
12911  // i.e. if the class hierarchies provably don't intersect.
12912 
12913  // TODO: it would be nice if "definitely valid" results were cached
12914  // in the UsingDecl and UsingShadowDecl so that these checks didn't
12915  // need to be repeated.
12916 
12918  auto Collect = [&Bases](const CXXRecordDecl *Base) {
12919  Bases.insert(Base);
12920  return true;
12921  };
12922 
12923  // Collect all bases. Return false if we find a dependent base.
12924  if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12925  return false;
12926 
12927  // Returns true if the base is dependent or is one of the accumulated base
12928  // classes.
12929  auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12930  return !Bases.count(Base);
12931  };
12932 
12933  // Return false if the class has a dependent base or if it or one
12934  // of its bases is present in the base set of the current context.
12935  if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12936  !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12937  return false;
12938 
12939  Diag(SS.getRange().getBegin(),
12940  diag::err_using_decl_nested_name_specifier_is_not_base_class)
12941  << SS.getScopeRep()
12942  << cast<CXXRecordDecl>(CurContext)
12943  << SS.getRange();
12944 
12945  return true;
12946 }
12947 
12949  MultiTemplateParamsArg TemplateParamLists,
12950  SourceLocation UsingLoc, UnqualifiedId &Name,
12951  const ParsedAttributesView &AttrList,
12952  TypeResult Type, Decl *DeclFromDeclSpec) {
12953  // Skip up to the relevant declaration scope.
12954  while (S->isTemplateParamScope())
12955  S = S->getParent();
12956  assert((S->getFlags() & Scope::DeclScope) &&
12957  "got alias-declaration outside of declaration scope");
12958 
12959  if (Type.isInvalid())
12960  return nullptr;
12961 
12962  bool Invalid = false;
12964  TypeSourceInfo *TInfo = nullptr;
12965  GetTypeFromParser(Type.get(), &TInfo);
12966 
12967  if (DiagnoseClassNameShadow(CurContext, NameInfo))
12968  return nullptr;
12969 
12970  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12972  Invalid = true;
12974  TInfo->getTypeLoc().getBeginLoc());
12975  }
12976 
12977  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12978  TemplateParamLists.size()
12981  LookupName(Previous, S);
12982 
12983  // Warn about shadowing the name of a template parameter.
12984  if (Previous.isSingleResult() &&
12985  Previous.getFoundDecl()->isTemplateParameter()) {
12986  DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12987  Previous.clear();
12988  }
12989 
12990  assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12991  "name in alias declaration must be an identifier");
12993  Name.StartLocation,
12994  Name.Identifier, TInfo);
12995 
12996  NewTD->setAccess(AS);
12997 
12998  if (Invalid)
12999  NewTD->setInvalidDecl();
13000 
13001  ProcessDeclAttributeList(S, NewTD, AttrList);
13002  AddPragmaAttributes(S, NewTD);
13003 
13005  Invalid |= NewTD->isInvalidDecl();
13006 
13007  bool Redeclaration = false;
13008 
13009  NamedDecl *NewND;
13010  if (TemplateParamLists.size()) {
13011  TypeAliasTemplateDecl *OldDecl = nullptr;
13012  TemplateParameterList *OldTemplateParams = nullptr;
13013 
13014  if (TemplateParamLists.size() != 1) {
13015  Diag(UsingLoc, diag::err_alias_template_extra_headers)
13016  << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13017  TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13018  }
13019  TemplateParameterList *TemplateParams = TemplateParamLists[0];
13020 
13021  // Check that we can declare a template here.
13022  if (CheckTemplateDeclScope(S, TemplateParams))
13023  return nullptr;
13024 
13025  // Only consider previous declarations in the same scope.
13026  FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13027  /*ExplicitInstantiationOrSpecialization*/false);
13028  if (!Previous.empty()) {
13029  Redeclaration = true;
13030 
13031  OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13032  if (!OldDecl && !Invalid) {
13033  Diag(UsingLoc, diag::err_redefinition_different_kind)
13034  << Name.Identifier;
13035 
13036  NamedDecl *OldD = Previous.getRepresentativeDecl();
13037  if (OldD->getLocation().isValid())
13038  Diag(OldD->getLocation(), diag::note_previous_definition);
13039 
13040  Invalid = true;
13041  }
13042 
13043  if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13044  if (TemplateParameterListsAreEqual(TemplateParams,
13045  OldDecl->getTemplateParameters(),
13046  /*Complain=*/true,
13048  OldTemplateParams =
13050  else
13051  Invalid = true;
13052 
13053  TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13054  if (!Invalid &&
13056  NewTD->getUnderlyingType())) {
13057  // FIXME: The C++0x standard does not clearly say this is ill-formed,
13058  // but we can't reasonably accept it.
13059  Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13060  << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13061  if (OldTD->getLocation().isValid())
13062  Diag(OldTD->getLocation(), diag::note_previous_definition);
13063  Invalid = true;
13064  }
13065  }
13066  }
13067 
13068  // Merge any previous default template arguments into our parameters,
13069  // and check the parameter list.
13070  if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13072  return nullptr;
13073 
13074  TypeAliasTemplateDecl *NewDecl =
13076  Name.Identifier, TemplateParams,
13077  NewTD);
13078  NewTD->setDescribedAliasTemplate(NewDecl);
13079 
13080  NewDecl->setAccess(AS);
13081 
13082  if (Invalid)
13083  NewDecl->setInvalidDecl();
13084  else if (OldDecl) {
13085  NewDecl->setPreviousDecl(OldDecl);
13086  CheckRedeclarationInModule(NewDecl, OldDecl);
13087  }
13088 
13089  NewND = NewDecl;
13090  } else {
13091  if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13092  setTagNameForLinkagePurposes(TD, NewTD);
13093  handleTagNumbering(TD, S);
13094  }
13095  ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13096  NewND = NewTD;
13097  }
13098 
13099  PushOnScopeChains(NewND, S);
13100  ActOnDocumentableDecl(NewND);
13101  return NewND;
13102 }
13103 
13105  SourceLocation AliasLoc,
13106  IdentifierInfo *Alias, CXXScopeSpec &SS,
13107  SourceLocation IdentLoc,
13108  IdentifierInfo *Ident) {
13109 
13110  // Lookup the namespace name.
13111  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13112  LookupParsedName(R, S, &SS);
13113 
13114  if (R.isAmbiguous())
13115  return nullptr;
13116 
13117  if (R.empty()) {
13118  if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13119  Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13120  return nullptr;
13121  }
13122  }
13123  assert(!R.isAmbiguous() && !R.empty());
13124  NamedDecl *ND = R.getRepresentativeDecl();
13125 
13126  // Check if we have a previous declaration with the same name.
13127  LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13129  LookupName(PrevR, S);
13130 
13131  // Check we're not shadowing a template parameter.
13132  if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13133  DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13134  PrevR.clear();
13135  }
13136 
13137  // Filter out any other lookup result from an enclosing scope.
13138  FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13139  /*AllowInlineNamespace*/false);
13140 
13141  // Find the previous declaration and check that we can redeclare it.
13142  NamespaceAliasDecl *Prev = nullptr;
13143  if (PrevR.isSingleResult()) {
13144  NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13145  if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13146  // We already have an alias with the same name that points to the same
13147  // namespace; check that it matches.
13148  if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13149  Prev = AD;
13150  } else if (isVisible(PrevDecl)) {
13151  Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13152  << Alias;
13153  Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13154  << AD->getNamespace();
13155  return nullptr;
13156  }
13157  } else if (isVisible(PrevDecl)) {
13158  unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13159  ? diag::err_redefinition
13160  : diag::err_redefinition_different_kind;
13161  Diag(AliasLoc, DiagID) << Alias;
13162  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13163  return nullptr;
13164  }
13165  }
13166 
13167  // The use of a nested name specifier may trigger deprecation warnings.
13168  DiagnoseUseOfDecl(ND, IdentLoc);
13169 
13171  NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13172  Alias, SS.getWithLocInContext(Context),
13173  IdentLoc, ND);
13174  if (Prev)
13175  AliasDecl->setPreviousDecl(Prev);
13176 
13178  return AliasDecl;
13179 }
13180 
13181 namespace {
13182 struct SpecialMemberExceptionSpecInfo
13183  : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13184  SourceLocation Loc;
13186 
13187  SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13190  SourceLocation Loc)
13191  : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13192 
13193  bool visitBase(CXXBaseSpecifier *Base);
13194  bool visitField(FieldDecl *FD);
13195 
13196  void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13197  unsigned Quals);
13198 
13199  void visitSubobjectCall(Subobject Subobj,
13201 };
13202 }
13203 
13204 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13205  auto *RT = Base->getType()->getAs<RecordType>();
13206  if (!RT)
13207  return false;
13208 
13209  auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13210  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13211  if (auto *BaseCtor = SMOR.getMethod()) {
13212  visitSubobjectCall(Base, BaseCtor);
13213  return false;
13214  }
13215 
13216  visitClassSubobject(BaseClass, Base, 0);
13217  return false;
13218 }
13219 
13220 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13221  if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13222  Expr *E = FD->getInClassInitializer();
13223  if (!E)
13224  // FIXME: It's a little wasteful to build and throw away a
13225  // CXXDefaultInitExpr here.
13226  // FIXME: We should have a single context note pointing at Loc, and
13227  // this location should be MD->getLocation() instead, since that's
13228  // the location where we actually use the default init expression.
13229  E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13230  if (E)
13231  ExceptSpec.CalledExpr(E);
13232  } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13233  ->getAs<RecordType>()) {
13234  visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13235  FD->getType().getCVRQualifiers());
13236  }
13237  return false;
13238 }
13239 
13240 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13241  Subobject Subobj,
13242  unsigned Quals) {
13243  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13244  bool IsMutable = Field && Field->isMutable();
13245  visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13246 }
13247 
13248 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13249  Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13250  // Note, if lookup fails, it doesn't matter what exception specification we
13251  // choose because the special member will be deleted.
13252  if (CXXMethodDecl *MD = SMOR.getMethod())
13253  ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13254 }
13255 
13257  llvm::APSInt Result;
13259  ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13260  ExplicitSpec.setExpr(Converted.get());
13261  if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13262  ExplicitSpec.setKind(Result.getBoolValue()
13265  return true;
13266  }
13267  ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13268  return false;
13269 }
13270 
13273  if (!ExplicitExpr->isTypeDependent())
13275  return ES;
13276 }
13277 
13282  ComputingExceptionSpec CES(S, MD, Loc);
13283 
13284  CXXRecordDecl *ClassDecl = MD->getParent();
13285 
13286  // C++ [except.spec]p14:
13287  // An implicitly declared special member function (Clause 12) shall have an
13288  // exception-specification. [...]
13289  SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13290  if (ClassDecl->isInvalidDecl())
13291  return Info.ExceptSpec;
13292 
13293  // FIXME: If this diagnostic fires, we're probably missing a check for
13294  // attempting to resolve an exception specification before it's known
13295  // at a higher level.
13296  if (S.RequireCompleteType(MD->getLocation(),
13297  S.Context.getRecordType(ClassDecl),
13298  diag::err_exception_spec_incomplete_type))
13299  return Info.ExceptSpec;
13300 
13301  // C++1z [except.spec]p7:
13302  // [Look for exceptions thrown by] a constructor selected [...] to
13303  // initialize a potentially constructed subobject,
13304  // C++1z [except.spec]p8:
13305  // The exception specification for an implicitly-declared destructor, or a
13306  // destructor without a noexcept-specifier, is potentially-throwing if and
13307  // only if any of the destructors for any of its potentially constructed
13308  // subojects is potentially throwing.
13309  // FIXME: We respect the first rule but ignore the "potentially constructed"
13310  // in the second rule to resolve a core issue (no number yet) that would have
13311  // us reject:
13312  // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13313  // struct B : A {};
13314  // struct C : B { void f(); };
13315  // ... due to giving B::~B() a non-throwing exception specification.
13316  Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13317  : Info.VisitAllBases);
13318 
13319  return Info.ExceptSpec;
13320 }
13321 
13322 namespace {
13323 /// RAII object to register a special member as being currently declared.
13324 struct DeclaringSpecialMember {
13325  Sema &S;
13327  Sema::ContextRAII SavedContext;
13328  bool WasAlreadyBeingDeclared;
13329 
13330  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13331  : S(S), D(RD, CSM), SavedContext(S, RD) {
13332  WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13333  if (WasAlreadyBeingDeclared)
13334  // This almost never happens, but if it does, ensure that our cache
13335  // doesn't contain a stale result.
13336  S.SpecialMemberCache.clear();
13337  else {
13338  // Register a note to be produced if we encounter an error while
13339  // declaring the special member.
13342  // FIXME: We don't have a location to use here. Using the class's
13343  // location maintains the fiction that we declare all special members
13344  // with the class, but (1) it's not clear that lying about that helps our
13345  // users understand what's going on, and (2) there may be outer contexts
13346  // on the stack (some of which are relevant) and printing them exposes
13347  // our lies.
13348  Ctx.PointOfInstantiation = RD->getLocation();
13349  Ctx.Entity = RD;
13350  Ctx.SpecialMember = CSM;
13351  S.pushCodeSynthesisContext(Ctx);
13352  }
13353  }
13354  ~DeclaringSpecialMember() {
13355  if (!WasAlreadyBeingDeclared) {
13356  S.SpecialMembersBeingDeclared.erase(D);
13358  }
13359  }
13360 
13361  /// Are we already trying to declare this special member?
13362  bool isAlreadyBeingDeclared() const {
13363  return WasAlreadyBeingDeclared;
13364  }
13365 };
13366 }
13367 
13369  // Look up any existing declarations, but don't trigger declaration of all
13370  // implicit special members with this name.
13371  DeclarationName Name = FD->getDeclName();
13374  for (auto *D : FD->getParent()->lookup(Name))
13375  if (auto *Acceptable = R.getAcceptableDecl(D))
13376  R.addDecl(Acceptable);
13377  R.resolveKind();
13378  R.suppressDiagnostics();
13379 
13380  CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
13381 }
13382 
13383 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13384  QualType ResultTy,
13385  ArrayRef<QualType> Args) {
13386  // Build an exception specification pointing back at this constructor.
13387  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13388 
13390  if (AS != LangAS::Default) {
13391  EPI.TypeQuals.addAddressSpace(AS);
13392  }
13393 
13394  auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13395  SpecialMem->setType(QT);
13396 
13397  // During template instantiation of implicit special member functions we need
13398  // a reliable TypeSourceInfo for the function prototype in order to allow
13399  // functions to be substituted.
13400  if (inTemplateInstantiation() &&
13401  cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13402  TypeSourceInfo *TSI =
13403  Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13404  SpecialMem->setTypeSourceInfo(TSI);
13405  }
13406 }
13407 
13409  CXXRecordDecl *ClassDecl) {
13410  // C++ [class.ctor]p5:
13411  // A default constructor for a class X is a constructor of class X
13412  // that can be called without an argument. If there is no
13413  // user-declared constructor for class X, a default constructor is
13414  // implicitly declared. An implicitly-declared default constructor
13415  // is an inline public member of its class.
13416  assert(ClassDecl->needsImplicitDefaultConstructor() &&
13417  "Should not build implicit default constructor!");
13418 
13419  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13420  if (DSM.isAlreadyBeingDeclared())
13421  return nullptr;
13422 
13423  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13425  false);
13426 
13427  // Create the actual constructor declaration.
13428  CanQualType ClassType
13430  SourceLocation ClassLoc = ClassDecl->getLocation();
13431  DeclarationName Name
13433  DeclarationNameInfo NameInfo(Name, ClassLoc);
13435  Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13436  /*TInfo=*/nullptr, ExplicitSpecifier(),
13437  getCurFPFeatures().isFPConstrained(),
13438  /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13441  DefaultCon->setAccess(AS_public);
13442  DefaultCon->setDefaulted();
13443 
13444  if (getLangOpts().CUDA) {
13446  DefaultCon,
13447  /* ConstRHS */ false,
13448  /* Diagnose */ false);
13449  }
13450 
13451  setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13452 
13453  // We don't need to use SpecialMemberIsTrivial here; triviality for default
13454  // constructors is easy to compute.
13455  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13456 
13457  // Note that we have declared this constructor.
13459 
13460  Scope *S = getScopeForContext(ClassDecl);
13462 
13464  SetDeclDeleted(DefaultCon, ClassLoc);
13465 
13466  if (S)
13467  PushOnScopeChains(DefaultCon, S, false);
13468  ClassDecl->addDecl(DefaultCon);
13469 
13470  return DefaultCon;
13471 }
13472 
13474  CXXConstructorDecl *Constructor) {
13475  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13476  !Constructor->doesThisDeclarationHaveABody() &&
13477  !Constructor->isDeleted()) &&
13478  "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13479  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13480  return;
13481 
13482  CXXRecordDecl *ClassDecl = Constructor->getParent();
13483  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13484 
13485  SynthesizedFunctionScope Scope(*this, Constructor);
13486 
13487  // The exception specification is needed because we are defining the
13488  // function.
13489  ResolveExceptionSpec(CurrentLocation,
13490  Constructor->getType()->castAs<FunctionProtoType>());
13491  MarkVTableUsed(CurrentLocation, ClassDecl);
13492 
13493  // Add a context note for diagnostics produced after this point.
13494  Scope.addContextNote(CurrentLocation);
13495 
13496  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13497  Constructor->setInvalidDecl();
13498  return;
13499  }
13500 
13501  SourceLocation Loc = Constructor->getEndLoc().isValid()
13502  ? Constructor->getEndLoc()
13503  : Constructor->getLocation();
13504  Constructor->setBody(new (Context) CompoundStmt(Loc));
13505  Constructor->markUsed(Context);
13506 
13508  L->CompletedImplicitDefinition(Constructor);
13509  }
13510 
13511  DiagnoseUninitializedFields(*this, Constructor);
13512 }
13513 
13515  // Perform any delayed checks on exception specifications.
13517 }
13518 
13519 /// Find or create the fake constructor we synthesize to model constructing an
13520 /// object of a derived class via a constructor of a base class.
13523  CXXConstructorDecl *BaseCtor,
13524  ConstructorUsingShadowDecl *Shadow) {
13525  CXXRecordDecl *Derived = Shadow->getParent();
13526  SourceLocation UsingLoc = Shadow->getLocation();
13527 
13528  // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13529  // For now we use the name of the base class constructor as a member of the
13530  // derived class to indicate a (fake) inherited constructor name.
13531  DeclarationName Name = BaseCtor->getDeclName();
13532 
13533  // Check to see if we already have a fake constructor for this inherited
13534  // constructor call.
13535  for (NamedDecl *Ctor : Derived->lookup(Name))
13536  if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13537  ->getInheritedConstructor()
13538  .getConstructor(),
13539  BaseCtor))
13540  return cast<CXXConstructorDecl>(Ctor);
13541 
13542  DeclarationNameInfo NameInfo(Name, UsingLoc);
13543  TypeSourceInfo *TInfo =
13544  Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13545  FunctionProtoTypeLoc ProtoLoc =
13547 
13548  // Check the inherited constructor is valid and find the list of base classes
13549  // from which it was inherited.
13550  InheritedConstructorInfo ICI(*this, Loc, Shadow);
13551 
13552  bool Constexpr =
13553  BaseCtor->isConstexpr() &&
13555  false, BaseCtor, &ICI);
13556 
13558  Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13559  BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13560  /*isInline=*/true,
13561  /*isImplicitlyDeclared=*/true,
13563  InheritedConstructor(Shadow, BaseCtor),
13564  BaseCtor->getTrailingRequiresClause());
13565  if (Shadow->isInvalidDecl())
13566  DerivedCtor->setInvalidDecl();
13567 
13568  // Build an unevaluated exception specification for this fake constructor.
13569  const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13572  EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13573  DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13574  FPT->getParamTypes(), EPI));
13575 
13576  // Build the parameter declarations.
13577  SmallVector<ParmVarDecl *, 16> ParamDecls;
13578  for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13579  TypeSourceInfo *TInfo =
13580  Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13582  Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13583  FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13584  PD->setScopeInfo(0, I);
13585  PD->setImplicit();
13586  // Ensure attributes are propagated onto parameters (this matters for
13587  // format, pass_object_size, ...).
13588  mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13589  ParamDecls.push_back(PD);
13590  ProtoLoc.setParam(I, PD);
13591  }
13592 
13593  // Set up the new constructor.
13594  assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13595  DerivedCtor->setAccess(BaseCtor->getAccess());
13596  DerivedCtor->setParams(ParamDecls);
13597  Derived->addDecl(DerivedCtor);
13598 
13599  if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13600  SetDeclDeleted(DerivedCtor, UsingLoc);
13601 
13602  return DerivedCtor;
13603 }
13604 
13606  InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13609  /*Diagnose*/true);
13610 }
13611 
13613  CXXConstructorDecl *Constructor) {
13614  CXXRecordDecl *ClassDecl = Constructor->getParent();
13615  assert(Constructor->getInheritedConstructor() &&
13616  !Constructor->doesThisDeclarationHaveABody() &&
13617  !Constructor->isDeleted());
13618  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13619  return;
13620 
13621  // Initializations are performed "as if by a defaulted default constructor",
13622  // so enter the appropriate scope.
13623  SynthesizedFunctionScope Scope(*this, Constructor);
13624 
13625  // The exception specification is needed because we are defining the
13626  // function.
13627  ResolveExceptionSpec(CurrentLocation,
13628  Constructor->getType()->castAs<FunctionProtoType>());
13629  MarkVTableUsed(CurrentLocation, ClassDecl);
13630 
13631  // Add a context note for diagnostics produced after this point.
13632  Scope.addContextNote(CurrentLocation);
13633 
13634  ConstructorUsingShadowDecl *Shadow =
13635  Constructor->getInheritedConstructor().getShadowDecl();
13636  CXXConstructorDecl *InheritedCtor =
13637  Constructor->getInheritedConstructor().getConstructor();
13638 
13639  // [class.inhctor.init]p1:
13640  // initialization proceeds as if a defaulted default constructor is used to
13641  // initialize the D object and each base class subobject from which the
13642  // constructor was inherited
13643 
13644  InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13645  CXXRecordDecl *RD = Shadow->getParent();
13646  SourceLocation InitLoc = Shadow->getLocation();
13647 
13648  // Build explicit initializers for all base classes from which the
13649  // constructor was inherited.
13651  for (bool VBase : {false, true}) {
13652  for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13653  if (B.isVirtual() != VBase)
13654  continue;
13655 
13656  auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13657  if (!BaseRD)
13658  continue;
13659 
13660  auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13661  if (!BaseCtor.first)
13662  continue;
13663 
13664  MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13666  InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13667 
13668  auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13669  Inits.push_back(new (Context) CXXCtorInitializer(
13670  Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13671  SourceLocation()));
13672  }
13673  }
13674 
13675  // We now proceed as if for a defaulted default constructor, with the relevant
13676  // initializers replaced.
13677 
13678  if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13679  Constructor->setInvalidDecl();
13680  return;
13681  }
13682 
13683  Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13684  Constructor->markUsed(Context);
13685 
13687  L->CompletedImplicitDefinition(Constructor);
13688  }
13689 
13690  DiagnoseUninitializedFields(*this, Constructor);
13691 }
13692 
13694  // C++ [class.dtor]p2:
13695  // If a class has no user-declared destructor, a destructor is
13696  // declared implicitly. An implicitly-declared destructor is an
13697  // inline public member of its class.
13698  assert(ClassDecl->needsImplicitDestructor());
13699 
13700  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13701  if (DSM.isAlreadyBeingDeclared())
13702  return nullptr;
13703 
13704  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13705  CXXDestructor,
13706  false);
13707 
13708  // Create the actual destructor declaration.
13709  CanQualType ClassType
13711  SourceLocation ClassLoc = ClassDecl->getLocation();
13712  DeclarationName Name
13714  DeclarationNameInfo NameInfo(Name, ClassLoc);
13716  Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13717  getCurFPFeatures().isFPConstrained(),
13718  /*isInline=*/true,
13719  /*isImplicitlyDeclared=*/true,
13722  Destructor->setAccess(AS_public);
13723  Destructor->setDefaulted();
13724 
13725  if (getLangOpts().CUDA) {
13727  Destructor,
13728  /* ConstRHS */ false,
13729  /* Diagnose */ false);
13730  }
13731 
13732  setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13733 
13734  // We don't need to use SpecialMemberIsTrivial here; triviality for
13735  // destructors is easy to compute.
13736  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13737  Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13738  ClassDecl->hasTrivialDestructorForCall());
13739 
13740  // Note that we have declared this destructor.
13742 
13743  Scope *S = getScopeForContext(ClassDecl);
13745 
13746  // We can't check whether an implicit destructor is deleted before we complete
13747  // the definition of the class, because its validity depends on the alignment
13748  // of the class. We'll check this from ActOnFields once the class is complete.
13749  if (ClassDecl->isCompleteDefinition() &&
13751  SetDeclDeleted(Destructor, ClassLoc);
13752 
13753  // Introduce this destructor into its scope.
13754  if (S)
13755  PushOnScopeChains(Destructor, S, false);
13756  ClassDecl->addDecl(Destructor);
13757 
13758  return Destructor;
13759 }
13760 
13762  CXXDestructorDecl *Destructor) {
13763  assert((Destructor->isDefaulted() &&
13764  !Destructor->doesThisDeclarationHaveABody() &&
13765  !Destructor->isDeleted()) &&
13766  "DefineImplicitDestructor - call it for implicit default dtor");
13767  if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13768  return;
13769 
13770  CXXRecordDecl *ClassDecl = Destructor->getParent();
13771  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13772 
13773  SynthesizedFunctionScope Scope(*this, Destructor);
13774 
13775  // The exception specification is needed because we are defining the
13776  // function.
13777  ResolveExceptionSpec(CurrentLocation,
13778  Destructor->getType()->castAs<FunctionProtoType>());
13779  MarkVTableUsed(CurrentLocation, ClassDecl);
13780 
13781  // Add a context note for diagnostics produced after this point.
13782  Scope.addContextNote(CurrentLocation);
13783 
13784  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13785  Destructor->getParent());
13786 
13787  if (CheckDestructor(Destructor)) {
13788  Destructor->setInvalidDecl();
13789  return;
13790  }
13791 
13792  SourceLocation Loc = Destructor->getEndLoc().isValid()
13793  ? Destructor->getEndLoc()
13794  : Destructor->getLocation();
13795  Destructor->setBody(new (Context) CompoundStmt(Loc));
13796  Destructor->markUsed(Context);
13797 
13799  L->CompletedImplicitDefinition(Destructor);
13800  }
13801 }
13802 
13804  CXXDestructorDecl *Destructor) {
13805  if (Destructor->isInvalidDecl())
13806  return;
13807 
13808  CXXRecordDecl *ClassDecl = Destructor->getParent();
13809  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13810  "implicit complete dtors unneeded outside MS ABI");
13811  assert(ClassDecl->getNumVBases() > 0 &&
13812  "complete dtor only exists for classes with vbases");
13813 
13814  SynthesizedFunctionScope Scope(*this, Destructor);
13815 
13816  // Add a context note for diagnostics produced after this point.
13817  Scope.addContextNote(CurrentLocation);
13818 
13819  MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13820 }
13821 
13822 /// Perform any semantic analysis which needs to be delayed until all
13823 /// pending class member declarations have been parsed.
13825  // If the context is an invalid C++ class, just suppress these checks.
13826  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13827  if (Record->isInvalidDecl()) {
13830  return;
13831  }
13833  }
13834 }
13835 
13838 
13839  if (!DelayedDllExportMemberFunctions.empty()) {
13841  std::swap(DelayedDllExportMemberFunctions, WorkList);
13842  for (CXXMethodDecl *M : WorkList) {
13843  DefineDefaultedFunction(*this, M, M->getLocation());
13844 
13845  // Pass the method to the consumer to get emitted. This is not necessary
13846  // for explicit instantiation definitions, as they will get emitted
13847  // anyway.
13848  if (M->getParent()->getTemplateSpecializationKind() !=
13851  }
13852  }
13853 }
13854 
13856  if (!DelayedDllExportClasses.empty()) {
13857  // Calling ReferenceDllExportedMembers might cause the current function to
13858  // be called again, so use a local copy of DelayedDllExportClasses.
13860  std::swap(DelayedDllExportClasses, WorkList);
13861  for (CXXRecordDecl *Class : WorkList)
13862  ReferenceDllExportedMembers(*this, Class);
13863  }
13864 }
13865 
13867  assert(getLangOpts().CPlusPlus11 &&
13868  "adjusting dtor exception specs was introduced in c++11");
13869 
13870  if (Destructor->isDependentContext())
13871  return;
13872 
13873  // C++11 [class.dtor]p3:
13874  // A declaration of a destructor that does not have an exception-
13875  // specification is implicitly considered to have the same exception-
13876  // specification as an implicit declaration.
13877  const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13878  if (DtorType->hasExceptionSpec())
13879  return;
13880 
13881  // Replace the destructor's type, building off the existing one. Fortunately,
13882  // the only thing of interest in the destructor type is its extended info.
13883  // The return and arguments are fixed.
13884  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13886  EPI.ExceptionSpec.SourceDecl = Destructor;
13887  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13888 
13889  // FIXME: If the destructor has a body that could throw, and the newly created
13890  // spec doesn't allow exceptions, we should emit a warning, because this
13891  // change in behavior can break conforming C++03 programs at runtime.
13892  // However, we don't have a body or an exception specification yet, so it
13893  // needs to be done somewhere else.
13894 }
13895 
13896 namespace {
13897 /// An abstract base class for all helper classes used in building the
13898 // copy/move operators. These classes serve as factory functions and help us
13899 // avoid using the same Expr* in the AST twice.
13900 class ExprBuilder {
13901  ExprBuilder(const ExprBuilder&) = delete;
13902  ExprBuilder &operator=(const ExprBuilder&) = delete;
13903 
13904 protected:
13905  static Expr *assertNotNull(Expr *E) {
13906  assert(E && "Expression construction must not fail.");
13907  return E;
13908  }
13909 
13910 public:
13911  ExprBuilder() {}
13912  virtual ~ExprBuilder() {}
13913 
13914  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13915 };
13916 
13917 class RefBuilder: public ExprBuilder {
13918  VarDecl *Var;
13919  QualType VarType;
13920 
13921 public:
13922  Expr *build(Sema &S, SourceLocation Loc) const override {
13923  return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13924  }
13925 
13926  RefBuilder(VarDecl *Var, QualType VarType)
13927  : Var(Var), VarType(VarType) {}
13928 };
13929 
13930 class ThisBuilder: public ExprBuilder {
13931 public:
13932  Expr *build(Sema &S, SourceLocation Loc) const override {
13933  return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13934  }
13935 };
13936 
13937 class CastBuilder: public ExprBuilder {
13938  const ExprBuilder &Builder;
13939  QualType Type;
13941  const CXXCastPath &Path;
13942 
13943 public:
13944  Expr *build(Sema &S, SourceLocation Loc) const override {
13945  return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13946  CK_UncheckedDerivedToBase, Kind,
13947  &Path).get());
13948  }
13949 
13950  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13951  const CXXCastPath &Path)
13952  : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13953 };
13954 
13955 class DerefBuilder: public ExprBuilder {
13956  const ExprBuilder &Builder;
13957 
13958 public:
13959  Expr *build(Sema &S, SourceLocation Loc) const override {
13960  return assertNotNull(
13961  S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13962  }
13963 
13964  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13965 };
13966 
13967 class MemberBuilder: public ExprBuilder {
13968  const ExprBuilder &Builder;
13969  QualType Type;
13970  CXXScopeSpec SS;
13971  bool IsArrow;
13972  LookupResult &MemberLookup;
13973 
13974 public:
13975  Expr *build(Sema &S, SourceLocation Loc) const override {
13976  return assertNotNull(S.BuildMemberReferenceExpr(
13977  Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13978  nullptr, MemberLookup, nullptr, nullptr).get());
13979  }
13980 
13981  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13982  LookupResult &MemberLookup)
13983  : Builder(Builder), Type(Type), IsArrow(IsArrow),
13984  MemberLookup(MemberLookup) {}
13985 };
13986 
13987 class MoveCastBuilder: public ExprBuilder {
13988  const ExprBuilder &Builder;
13989 
13990 public:
13991  Expr *build(Sema &S, SourceLocation Loc) const override {
13992  return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13993  }
13994 
13995  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13996 };
13997 
13998 class LvalueConvBuilder: public ExprBuilder {
13999  const ExprBuilder &Builder;
14000 
14001 public:
14002  Expr *build(Sema &S, SourceLocation Loc) const override {
14003  return assertNotNull(
14004  S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14005  }
14006 
14007  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14008 };
14009 
14010 class SubscriptBuilder: public ExprBuilder {
14011  const ExprBuilder &Base;
14012  const ExprBuilder &Index;
14013 
14014 public:
14015  Expr *build(Sema &S, SourceLocation Loc) const override {
14016  return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14017  Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14018  }
14019 
14020  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14021  : Base(Base), Index(Index) {}
14022 };
14023 
14024 } // end anonymous namespace
14025 
14026 /// When generating a defaulted copy or move assignment operator, if a field
14027 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14028 /// do so. This optimization only applies for arrays of scalars, and for arrays
14029 /// of class type where the selected copy/move-assignment operator is trivial.
14030 static StmtResult
14032  const ExprBuilder &ToB, const ExprBuilder &FromB) {
14033  // Compute the size of the memory buffer to be copied.
14034  QualType SizeType = S.Context.getSizeType();
14035  llvm::APInt Size(S.Context.getTypeSize(SizeType),
14037 
14038  // Take the address of the field references for "from" and "to". We
14039  // directly construct UnaryOperators here because semantic analysis
14040  // does not permit us to take the address of an xvalue.
14041  Expr *From = FromB.build(S, Loc);
14042  From = UnaryOperator::Create(
14043  S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14044  VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14045  Expr *To = ToB.build(S, Loc);
14046  To = UnaryOperator::Create(
14047  S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14048  VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14049 
14050  const Type *E = T->getBaseElementTypeUnsafe();
14051  bool NeedsCollectableMemCpy =
14052  E->isRecordType() &&
14053  E->castAs<RecordType>()->getDecl()->hasObjectMember();
14054 
14055  // Create a reference to the __builtin_objc_memmove_collectable function
14056  StringRef MemCpyName = NeedsCollectableMemCpy ?
14057  "__builtin_objc_memmove_collectable" :
14058  "__builtin_memcpy";
14059  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14061  S.LookupName(R, S.TUScope, true);
14062 
14063  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14064  if (!MemCpy)
14065  // Something went horribly wrong earlier, and we will have complained
14066  // about it.
14067  return StmtError();
14068 
14069  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14070  VK_PRValue, Loc, nullptr);
14071  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14072 
14073  Expr *CallArgs[] = {
14074  To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14075  };
14076  ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14077  Loc, CallArgs, Loc);
14078 
14079  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14080  return Call.getAs<Stmt>();
14081 }
14082 
14083 /// Builds a statement that copies/moves the given entity from \p From to
14084 /// \c To.
14085 ///
14086 /// This routine is used to copy/move the members of a class with an
14087 /// implicitly-declared copy/move assignment operator. When the entities being
14088 /// copied are arrays, this routine builds for loops to copy them.
14089 ///
14090 /// \param S The Sema object used for type-checking.
14091 ///
14092 /// \param Loc The location where the implicit copy/move is being generated.
14093 ///
14094 /// \param T The type of the expressions being copied/moved. Both expressions
14095 /// must have this type.
14096 ///
14097 /// \param To The expression we are copying/moving to.
14098 ///
14099 /// \param From The expression we are copying/moving from.
14100 ///
14101 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14102 /// Otherwise, it's a non-static member subobject.
14103 ///
14104 /// \param Copying Whether we're copying or moving.
14105 ///
14106 /// \param Depth Internal parameter recording the depth of the recursion.
14107 ///
14108 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14109 /// if a memcpy should be used instead.
14110 static StmtResult
14112  const ExprBuilder &To, const ExprBuilder &From,
14113  bool CopyingBaseSubobject, bool Copying,
14114  unsigned Depth = 0) {
14115  // C++11 [class.copy]p28:
14116  // Each subobject is assigned in the manner appropriate to its type:
14117  //
14118  // - if the subobject is of class type, as if by a call to operator= with
14119  // the subobject as the object expression and the corresponding
14120  // subobject of x as a single function argument (as if by explicit
14121  // qualification; that is, ignoring any possible virtual overriding
14122  // functions in more derived classes);
14123  //
14124  // C++03 [class.copy]p13:
14125  // - if the subobject is of class type, the copy assignment operator for
14126  // the class is used (as if by explicit qualification; that is,
14127  // ignoring any possible virtual overriding functions in more derived
14128  // classes);
14129  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14130  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14131 
14132  // Look for operator=.
14133  DeclarationName Name
14135  LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14136  S.LookupQualifiedName(OpLookup, ClassDecl, false);
14137 
14138  // Prior to C++11, filter out any result that isn't a copy/move-assignment
14139  // operator.
14140  if (!S.getLangOpts().CPlusPlus11) {
14141  LookupResult::Filter F = OpLookup.makeFilter();
14142  while (F.hasNext()) {
14143  NamedDecl *D = F.next();
14144  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14145  if (Method->isCopyAssignmentOperator() ||
14146  (!Copying && Method->isMoveAssignmentOperator()))
14147  continue;
14148 
14149  F.erase();
14150  }
14151  F.done();
14152  }
14153 
14154  // Suppress the protected check (C++ [class.protected]) for each of the
14155  // assignment operators we found. This strange dance is required when
14156  // we're assigning via a base classes's copy-assignment operator. To
14157  // ensure that we're getting the right base class subobject (without
14158  // ambiguities), we need to cast "this" to that subobject type; to
14159  // ensure that we don't go through the virtual call mechanism, we need
14160  // to qualify the operator= name with the base class (see below). However,
14161  // this means that if the base class has a protected copy assignment
14162  // operator, the protected member access check will fail. So, we
14163  // rewrite "protected" access to "public" access in this case, since we
14164  // know by construction that we're calling from a derived class.
14165  if (CopyingBaseSubobject) {
14166  for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14167  L != LEnd; ++L) {
14168  if (L.getAccess() == AS_protected)
14169  L.setAccess(AS_public);
14170  }
14171  }
14172 
14173  // Create the nested-name-specifier that will be used to qualify the
14174  // reference to operator=; this is required to suppress the virtual
14175  // call mechanism.
14176  CXXScopeSpec SS;
14177  const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14178  SS.MakeTrivial(S.Context,
14179  NestedNameSpecifier::Create(S.Context, nullptr, false,
14180  CanonicalT),
14181  Loc);
14182 
14183  // Create the reference to operator=.
14184  ExprResult OpEqualRef
14185  = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14186  SS, /*TemplateKWLoc=*/SourceLocation(),
14187  /*FirstQualifierInScope=*/nullptr,
14188  OpLookup,
14189  /*TemplateArgs=*/nullptr, /*S*/nullptr,
14190  /*SuppressQualifierCheck=*/true);
14191  if (OpEqualRef.isInvalid())
14192  return StmtError();
14193 
14194  // Build the call to the assignment operator.
14195 
14196  Expr *FromInst = From.build(S, Loc);
14197  ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14198  OpEqualRef.getAs<Expr>(),
14199  Loc, FromInst, Loc);
14200  if (Call.isInvalid())
14201  return StmtError();
14202 
14203  // If we built a call to a trivial 'operator=' while copying an array,
14204  // bail out. We'll replace the whole shebang with a memcpy.
14205  CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14206  if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14207  return StmtResult((Stmt*)nullptr);
14208 
14209  // Convert to an expression-statement, and clean up any produced
14210  // temporaries.
14211  return S.ActOnExprStmt(Call);
14212  }
14213 
14214  // - if the subobject is of scalar type, the built-in assignment
14215  // operator is used.
14216  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14217  if (!ArrayTy) {
14219  Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14220  if (Assignment.isInvalid())
14221  return StmtError();
14222  return S.ActOnExprStmt(Assignment);
14223  }
14224 
14225  // - if the subobject is an array, each element is assigned, in the
14226  // manner appropriate to the element type;
14227 
14228  // Construct a loop over the array bounds, e.g.,
14229  //
14230  // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14231  //
14232  // that will copy each of the array elements.
14233  QualType SizeType = S.Context.getSizeType();
14234 
14235  // Create the iteration variable.
14236  IdentifierInfo *IterationVarName = nullptr;
14237  {
14238  SmallString<8> Str;
14239  llvm::raw_svector_ostream OS(Str);
14240  OS << "__i" << Depth;
14241  IterationVarName = &S.Context.Idents.get(OS.str());
14242  }
14243  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14244  IterationVarName, SizeType,
14245  S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14246  SC_None);
14247 
14248  // Initialize the iteration variable to zero.
14249  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14250  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14251 
14252  // Creates a reference to the iteration variable.
14253  RefBuilder IterationVarRef(IterationVar, SizeType);
14254  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14255 
14256  // Create the DeclStmt that holds the iteration variable.
14257  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14258 
14259  // Subscript the "from" and "to" expressions with the iteration variable.
14260  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14261  MoveCastBuilder FromIndexMove(FromIndexCopy);
14262  const ExprBuilder *FromIndex;
14263  if (Copying)
14264  FromIndex = &FromIndexCopy;
14265  else
14266  FromIndex = &FromIndexMove;
14267 
14268  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14269 
14270  // Build the copy/move for an individual element of the array.
14271  StmtResult Copy =
14273  ToIndex, *FromIndex, CopyingBaseSubobject,
14274  Copying, Depth + 1);
14275  // Bail out if copying fails or if we determined that we should use memcpy.
14276  if (Copy.isInvalid() || !Copy.get())
14277  return Copy;
14278 
14279  // Create the comparison against the array bound.
14280  llvm::APInt Upper
14281  = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14282  Expr *Comparison = BinaryOperator::Create(
14283  S.Context, IterationVarRefRVal.build(S, Loc),
14284  IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14286  S.CurFPFeatureOverrides());
14287 
14288  // Create the pre-increment of the iteration variable. We can determine
14289  // whether the increment will overflow based on the value of the array
14290  // bound.
14291  Expr *Increment = UnaryOperator::Create(
14292  S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14293  OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14294 
14295  // Construct the loop that copies all elements of this array.
14296  return S.ActOnForStmt(
14297  Loc, Loc, InitStmt,
14298  S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14299  S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14300 }
14301 
14302 static StmtResult
14304  const ExprBuilder &To, const ExprBuilder &From,
14305  bool CopyingBaseSubobject, bool Copying) {
14306  // Maybe we should use a memcpy?
14307  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14309  return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14310 
14311  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14312  CopyingBaseSubobject,
14313  Copying, 0));
14314 
14315  // If we ended up picking a trivial assignment operator for an array of a
14316  // non-trivially-copyable class type, just emit a memcpy.
14317  if (!Result.isInvalid() && !Result.get())
14318  return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14319 
14320  return Result;
14321 }
14322 
14324  // Note: The following rules are largely analoguous to the copy
14325  // constructor rules. Note that virtual bases are not taken into account
14326  // for determining the argument type of the operator. Note also that
14327  // operators taking an object instead of a reference are allowed.
14328  assert(ClassDecl->needsImplicitCopyAssignment());
14329 
14330  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14331  if (DSM.isAlreadyBeingDeclared())
14332  return nullptr;
14333 
14334  QualType ArgType = Context.getTypeDeclType(ClassDecl);
14336  if (AS != LangAS::Default)
14337  ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14338  QualType RetType = Context.getLValueReferenceType(ArgType);
14339  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14340  if (Const)
14341  ArgType = ArgType.withConst();
14342 
14343  ArgType = Context.getLValueReferenceType(ArgType);
14344 
14345  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14347  Const);
14348 
14349  // An implicitly-declared copy assignment operator is an inline public
14350  // member of its class.
14352  SourceLocation ClassLoc = ClassDecl->getLocation();
14353  DeclarationNameInfo NameInfo(Name, ClassLoc);
14354  CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14355  Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14356  /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14357  getCurFPFeatures().isFPConstrained(),
14358  /*isInline=*/true,
14360  SourceLocation());
14361  CopyAssignment->setAccess(AS_public);
14362  CopyAssignment->setDefaulted();
14363  CopyAssignment->setImplicit();
14364 
14365  if (getLangOpts().CUDA) {
14367  CopyAssignment,
14368  /* ConstRHS */ Const,
14369  /* Diagnose */ false);
14370  }
14371 
14372  setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14373 
14374  // Add the parameter to the operator.
14375  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14376  ClassLoc, ClassLoc,
14377  /*Id=*/nullptr, ArgType,
14378  /*TInfo=*/nullptr, SC_None,
14379  nullptr);
14380  CopyAssignment->setParams(FromParam);
14381 
14382  CopyAssignment->setTrivial(
14384  ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14385  : ClassDecl->hasTrivialCopyAssignment());
14386 
14387  // Note that we have added this copy-assignment operator.
14389 
14390  Scope *S = getScopeForContext(ClassDecl);
14391  CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14392 
14393  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14395  SetDeclDeleted(CopyAssignment, ClassLoc);
14396  }
14397 
14398  if (S)
14399  PushOnScopeChains(CopyAssignment, S, false);
14400  ClassDecl->addDecl(CopyAssignment);
14401 
14402  return CopyAssignment;
14403 }
14404 
14405 /// Diagnose an implicit copy operation for a class which is odr-used, but
14406 /// which is deprecated because the class has a user-declared copy constructor,
14407 /// copy assignment operator, or destructor.
14409  assert(CopyOp->isImplicit());
14410 
14411  CXXRecordDecl *RD = CopyOp->getParent();
14412  CXXMethodDecl *UserDeclaredOperation = nullptr;
14413 
14414  // In Microsoft mode, assignment operations don't affect constructors and
14415  // vice versa.
14416  if (RD->hasUserDeclaredDestructor()) {
14417  UserDeclaredOperation = RD->getDestructor();
14418  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14420  !S.getLangOpts().MSVCCompat) {
14421  // Find any user-declared copy constructor.
14422  for (auto *I : RD->ctors()) {
14423  if (I->isCopyConstructor()) {
14424  UserDeclaredOperation = I;
14425  break;
14426  }
14427  }
14428  assert(UserDeclaredOperation);
14429  } else if (isa<CXXConstructorDecl>(CopyOp) &&
14431  !S.getLangOpts().MSVCCompat) {
14432  // Find any user-declared move assignment operator.
14433  for (auto *I : RD->methods()) {
14434  if (I->isCopyAssignmentOperator()) {
14435  UserDeclaredOperation = I;
14436  break;
14437  }
14438  }
14439  assert(UserDeclaredOperation);
14440  }
14441 
14442  if (UserDeclaredOperation) {
14443  bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14444  bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14445  bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14446  unsigned DiagID =
14447  (UDOIsUserProvided && UDOIsDestructor)
14448  ? diag::warn_deprecated_copy_with_user_provided_dtor
14449  : (UDOIsUserProvided && !UDOIsDestructor)
14450  ? diag::warn_deprecated_copy_with_user_provided_copy
14451  : (!UDOIsUserProvided && UDOIsDestructor)
14452  ? diag::warn_deprecated_copy_with_dtor
14453  : diag::warn_deprecated_copy;
14454  S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14455  << RD << IsCopyAssignment;
14456  }
14457 }
14458 
14460  CXXMethodDecl *CopyAssignOperator) {
14461  assert((CopyAssignOperator->isDefaulted() &&
14462  CopyAssignOperator->isOverloadedOperator() &&
14463  CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14464  !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14465  !CopyAssignOperator->isDeleted()) &&
14466  "DefineImplicitCopyAssignment called for wrong function");
14467  if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14468  return;
14469 
14470  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14471  if (ClassDecl->isInvalidDecl()) {
14472  CopyAssignOperator->setInvalidDecl();
14473  return;
14474  }
14475 
14476  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14477 
14478  // The exception specification is needed because we are defining the
14479  // function.
14480  ResolveExceptionSpec(CurrentLocation,
14481  CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14482 
14483  // Add a context note for diagnostics produced after this point.
14484  Scope.addContextNote(CurrentLocation);
14485 
14486  // C++11 [class.copy]p18:
14487  // The [definition of an implicitly declared copy assignment operator] is
14488  // deprecated if the class has a user-declared copy constructor or a
14489  // user-declared destructor.
14490  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14491  diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14492 
14493  // C++0x [class.copy]p30:
14494  // The implicitly-defined or explicitly-defaulted copy assignment operator
14495  // for a non-union class X performs memberwise copy assignment of its
14496  // subobjects. The direct base classes of X are assigned first, in the
14497  // order of their declaration in the base-specifier-list, and then the
14498  // immediate non-static data members of X are assigned, in the order in
14499  // which they were declared in the class definition.
14500 
14501  // The statements that form the synthesized function body.
14502  SmallVector<Stmt*, 8> Statements;
14503 
14504  // The parameter for the "other" object, which we are copying from.
14505  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14506  Qualifiers OtherQuals = Other->getType().getQualifiers();
14507  QualType OtherRefType = Other->getType();
14508  if (const LValueReferenceType *OtherRef
14509  = OtherRefType->getAs<LValueReferenceType>()) {
14510  OtherRefType = OtherRef->getPointeeType();
14511  OtherQuals = OtherRefType.getQualifiers();
14512  }
14513 
14514  // Our location for everything implicitly-generated.
14515  SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14516  ? CopyAssignOperator->getEndLoc()
14517  : CopyAssignOperator->getLocation();
14518 
14519  // Builds a DeclRefExpr for the "other" object.
14520  RefBuilder OtherRef(Other, OtherRefType);
14521 
14522  // Builds the "this" pointer.
14523  ThisBuilder This;
14524 
14525  // Assign base classes.
14526  bool Invalid = false;
14527  for (auto &Base : ClassDecl->bases()) {
14528  // Form the assignment:
14529  // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14530  QualType BaseType = Base.getType().getUnqualifiedType();
14531  if (!BaseType->isRecordType()) {
14532  Invalid = true;
14533  continue;
14534  }
14535 
14536  CXXCastPath BasePath;
14537  BasePath.push_back(&Base);
14538 
14539  // Construct the "from" expression, which is an implicit cast to the
14540  // appropriately-qualified base type.
14541  CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14542  VK_LValue, BasePath);
14543 
14544  // Dereference "this".
14545  DerefBuilder DerefThis(This);
14546  CastBuilder To(DerefThis,
14548  BaseType, CopyAssignOperator->getMethodQualifiers()),
14549  VK_LValue, BasePath);
14550 
14551  // Build the copy.
14552  StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14553  To, From,
14554  /*CopyingBaseSubobject=*/true,
14555  /*Copying=*/true);
14556  if (Copy.isInvalid()) {
14557  CopyAssignOperator->setInvalidDecl();
14558  return;
14559  }
14560 
14561  // Success! Record the copy.
14562  Statements.push_back(Copy.getAs<Expr>());
14563  }
14564 
14565  // Assign non-static members.
14566  for (auto *Field : ClassDecl->fields()) {
14567  // FIXME: We should form some kind of AST representation for the implied
14568  // memcpy in a union copy operation.
14569  if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14570  continue;
14571 
14572  if (Field->isInvalidDecl()) {
14573  Invalid = true;
14574  continue;
14575  }
14576 
14577  // Check for members of reference type; we can't copy those.
14578  if (Field->getType()->isReferenceType()) {
14579  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14580  << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14581  Diag(Field->getLocation(), diag::note_declared_at);
14582  Invalid = true;
14583  continue;
14584  }
14585 
14586  // Check for members of const-qualified, non-class type.
14587  QualType BaseType = Context.getBaseElementType(Field->getType());
14588  if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14589  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14590  << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14591  Diag(Field->getLocation(), diag::note_declared_at);
14592  Invalid = true;
14593  continue;
14594  }
14595 
14596  // Suppress assigning zero-width bitfields.
14597  if (Field->isZeroLengthBitField(Context))
14598  continue;
14599 
14600  QualType FieldType = Field->getType().getNonReferenceType();
14601  if (FieldType->isIncompleteArrayType()) {
14602  assert(ClassDecl->hasFlexibleArrayMember() &&
14603  "Incomplete array type is not valid");
14604  continue;
14605  }
14606 
14607  // Build references to the field in the object we're copying from and to.
14608  CXXScopeSpec SS; // Intentionally empty
14609  LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14611  MemberLookup.addDecl(Field);
14612  MemberLookup.resolveKind();
14613 
14614  MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14615 
14616  MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14617 
14618  // Build the copy of this field.
14619  StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14620  To, From,
14621  /*CopyingBaseSubobject=*/false,
14622  /*Copying=*/true);
14623  if (Copy.isInvalid()) {
14624  CopyAssignOperator->setInvalidDecl();
14625  return;
14626  }
14627 
14628  // Success! Record the copy.
14629  Statements.push_back(Copy.getAs<Stmt>());
14630  }
14631 
14632  if (!Invalid) {
14633  // Add a "return *this;"
14634  ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14635 
14636  StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14637  if (Return.isInvalid())
14638  Invalid = true;
14639  else
14640  Statements.push_back(Return.getAs<Stmt>());
14641  }
14642 
14643  if (Invalid) {
14644  CopyAssignOperator->setInvalidDecl();
14645  return;
14646  }
14647 
14648  StmtResult Body;
14649  {
14650  CompoundScopeRAII CompoundScope(*this);
14651  Body = ActOnCompoundStmt(Loc, Loc, Statements,
14652  /*isStmtExpr=*/false);
14653  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14654  }
14655  CopyAssignOperator->setBody(Body.getAs<Stmt>());
14656  CopyAssignOperator->markUsed(Context);
14657 
14659  L->CompletedImplicitDefinition(CopyAssignOperator);
14660  }
14661 }
14662 
14664  assert(ClassDecl->needsImplicitMoveAssignment());
14665 
14666  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14667  if (DSM.isAlreadyBeingDeclared())
14668  return nullptr;
14669 
14670  // Note: The following rules are largely analoguous to the move
14671  // constructor rules.
14672 
14673  QualType ArgType = Context.getTypeDeclType(ClassDecl);
14675  if (AS != LangAS::Default)
14676  ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14677  QualType RetType = Context.getLValueReferenceType(ArgType);
14678  ArgType = Context.getRValueReferenceType(ArgType);
14679 
14680  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14682  false);
14683 
14684  // An implicitly-declared move assignment operator is an inline public
14685  // member of its class.
14687  SourceLocation ClassLoc = ClassDecl->getLocation();
14688  DeclarationNameInfo NameInfo(Name, ClassLoc);
14689  CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14690  Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14691  /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14692  getCurFPFeatures().isFPConstrained(),
14693  /*isInline=*/true,
14695  SourceLocation());
14696  MoveAssignment->setAccess(AS_public);
14697  MoveAssignment->setDefaulted();
14698  MoveAssignment->setImplicit();
14699 
14700  if (getLangOpts().CUDA) {
14702  MoveAssignment,
14703  /* ConstRHS */ false,
14704  /* Diagnose */ false);
14705  }
14706 
14707  setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14708 
14709  // Add the parameter to the operator.
14710  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14711  ClassLoc, ClassLoc,
14712  /*Id=*/nullptr, ArgType,
14713  /*TInfo=*/nullptr, SC_None,
14714  nullptr);
14715  MoveAssignment->setParams(FromParam);
14716 
14717  MoveAssignment->setTrivial(
14719  ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14720  : ClassDecl->hasTrivialMoveAssignment());
14721 
14722  // Note that we have added this copy-assignment operator.
14724 
14725  Scope *S = getScopeForContext(ClassDecl);
14726  CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14727 
14728  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14730  SetDeclDeleted(MoveAssignment, ClassLoc);
14731  }
14732 
14733  if (S)
14734  PushOnScopeChains(MoveAssignment, S, false);
14735  ClassDecl->addDecl(MoveAssignment);
14736 
14737  return MoveAssignment;
14738 }
14739 
14740 /// Check if we're implicitly defining a move assignment operator for a class
14741 /// with virtual bases. Such a move assignment might move-assign the virtual
14742 /// base multiple times.
14744  SourceLocation CurrentLocation) {
14745  assert(!Class->isDependentContext() && "should not define dependent move");
14746 
14747  // Only a virtual base could get implicitly move-assigned multiple times.
14748  // Only a non-trivial move assignment can observe this. We only want to
14749  // diagnose if we implicitly define an assignment operator that assigns
14750  // two base classes, both of which move-assign the same virtual base.
14751  if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14752  Class->getNumBases() < 2)
14753  return;
14754 
14756  typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14757  VBaseMap VBases;
14758 
14759  for (auto &BI : Class->bases()) {
14760  Worklist.push_back(&BI);
14761  while (!Worklist.empty()) {
14762  CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14763  CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14764 
14765  // If the base has no non-trivial move assignment operators,
14766  // we don't care about moves from it.
14767  if (!Base->hasNonTrivialMoveAssignment())
14768  continue;
14769 
14770  // If there's nothing virtual here, skip it.
14771  if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14772  continue;
14773 
14774  // If we're not actually going to call a move assignment for this base,
14775  // or the selected move assignment is trivial, skip it.
14778  /*ConstArg*/false, /*VolatileArg*/false,
14779  /*RValueThis*/true, /*ConstThis*/false,
14780  /*VolatileThis*/false);
14781  if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14783  continue;
14784 
14785  if (BaseSpec->isVirtual()) {
14786  // We're going to move-assign this virtual base, and its move
14787  // assignment operator is not trivial. If this can happen for
14788  // multiple distinct direct bases of Class, diagnose it. (If it
14789  // only happens in one base, we'll diagnose it when synthesizing
14790  // that base class's move assignment operator.)
14791  CXXBaseSpecifier *&Existing =
14792  VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14793  .first->second;
14794  if (Existing && Existing != &BI) {
14795  S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14796  << Class << Base;
14797  S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14798  << (Base->getCanonicalDecl() ==
14799  Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14800  << Base << Existing->getType() << Existing->getSourceRange();
14801  S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14802  << (Base->getCanonicalDecl() ==
14803  BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14804  << Base << BI.getType() << BaseSpec->getSourceRange();
14805 
14806  // Only diagnose each vbase once.
14807  Existing = nullptr;
14808  }
14809  } else {
14810  // Only walk over bases that have defaulted move assignment operators.
14811  // We assume that any user-provided move assignment operator handles
14812  // the multiple-moves-of-vbase case itself somehow.
14813  if (!SMOR.getMethod()->isDefaulted())
14814  continue;
14815 
14816  // We're going to move the base classes of Base. Add them to the list.
14817  llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14818  }
14819  }
14820  }
14821 }
14822 
14824  CXXMethodDecl *MoveAssignOperator) {
14825  assert((MoveAssignOperator->isDefaulted() &&
14826  MoveAssignOperator->isOverloadedOperator() &&
14827  MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14828  !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14829  !MoveAssignOperator->isDeleted()) &&
14830  "DefineImplicitMoveAssignment called for wrong function");
14831  if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14832  return;
14833 
14834  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14835  if (ClassDecl->isInvalidDecl()) {
14836  MoveAssignOperator->setInvalidDecl();
14837  return;
14838  }
14839 
14840  // C++0x [class.copy]p28:
14841  // The implicitly-defined or move assignment operator for a non-union class
14842  // X performs memberwise move assignment of its subobjects. The direct base
14843  // classes of X are assigned first, in the order of their declaration in the
14844  // base-specifier-list, and then the immediate non-static data members of X
14845  // are assigned, in the order in which they were declared in the class
14846  // definition.
14847 
14848  // Issue a warning if our implicit move assignment operator will move
14849  // from a virtual base more than once.
14850  checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14851 
14852  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14853 
14854  // The exception specification is needed because we are defining the
14855  // function.
14856  ResolveExceptionSpec(CurrentLocation,
14857  MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14858 
14859  // Add a context note for diagnostics produced after this point.
14860  Scope.addContextNote(CurrentLocation);
14861 
14862  // The statements that form the synthesized function body.
14863  SmallVector<Stmt*, 8> Statements;
14864 
14865  // The parameter for the "other" object, which we are move from.
14866  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14867  QualType OtherRefType =
14868  Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14869 
14870  // Our location for everything implicitly-generated.
14871  SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14872  ? MoveAssignOperator->getEndLoc()
14873  : MoveAssignOperator->getLocation();
14874 
14875  // Builds a reference to the "other" object.
14876  RefBuilder OtherRef(Other, OtherRefType);
14877  // Cast to rvalue.
14878  MoveCastBuilder MoveOther(OtherRef);
14879 
14880  // Builds the "this" pointer.
14881  ThisBuilder This;
14882 
14883  // Assign base classes.
14884  bool Invalid = false;
14885  for (auto &Base : ClassDecl->bases()) {
14886  // C++11 [class.copy]p28:
14887  // It is unspecified whether subobjects representing virtual base classes
14888  // are assigned more than once by the implicitly-defined copy assignment
14889  // operator.
14890  // FIXME: Do not assign to a vbase that will be assigned by some other base
14891  // class. For a move-assignment, this can result in the vbase being moved
14892  // multiple times.
14893 
14894  // Form the assignment:
14895  // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14896  QualType BaseType = Base.getType().getUnqualifiedType();
14897  if (!BaseType->isRecordType()) {
14898  Invalid = true;
14899  continue;
14900  }
14901 
14902  CXXCastPath BasePath;
14903  BasePath.push_back(&Base);
14904 
14905  // Construct the "from" expression, which is an implicit cast to the
14906  // appropriately-qualified base type.
14907  CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14908 
14909  // Dereference "this".
14910  DerefBuilder DerefThis(This);
14911 
14912  // Implicitly cast "this" to the appropriately-qualified base type.
14913  CastBuilder To(DerefThis,
14915  BaseType, MoveAssignOperator->getMethodQualifiers()),
14916  VK_LValue, BasePath);
14917 
14918  // Build the move.
14919  StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14920  To, From,
14921  /*CopyingBaseSubobject=*/true,
14922  /*Copying=*/false);
14923  if (Move.isInvalid()) {
14924  MoveAssignOperator->setInvalidDecl();
14925  return;
14926  }
14927 
14928  // Success! Record the move.
14929  Statements.push_back(Move.getAs<Expr>());
14930  }
14931 
14932  // Assign non-static members.
14933  for (auto *Field : ClassDecl->fields()) {
14934  // FIXME: We should form some kind of AST representation for the implied
14935  // memcpy in a union copy operation.
14936  if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14937  continue;
14938 
14939  if (Field->isInvalidDecl()) {
14940  Invalid = true;
14941  continue;
14942  }
14943 
14944  // Check for members of reference type; we can't move those.
14945  if (Field->getType()->isReferenceType()) {
14946  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14947  << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14948  Diag(Field->getLocation(), diag::note_declared_at);
14949  Invalid = true;
14950  continue;
14951  }
14952 
14953  // Check for members of const-qualified, non-class type.
14954  QualType BaseType = Context.getBaseElementType(Field->getType());
14955  if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14956  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14957  << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14958  Diag(Field->getLocation(), diag::note_declared_at);
14959  Invalid = true;
14960  continue;
14961  }
14962 
14963  // Suppress assigning zero-width bitfields.
14964  if (Field->isZeroLengthBitField(Context))
14965  continue;
14966 
14967  QualType FieldType = Field->getType().getNonReferenceType();
14968  if (FieldType->isIncompleteArrayType()) {
14969  assert(ClassDecl->hasFlexibleArrayMember() &&
14970  "Incomplete array type is not valid");
14971  continue;
14972  }
14973 
14974  // Build references to the field in the object we're copying from and to.
14975  LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14977  MemberLookup.addDecl(Field);
14978  MemberLookup.resolveKind();
14979  MemberBuilder From(MoveOther, OtherRefType,
14980  /*IsArrow=*/false, MemberLookup);
14981  MemberBuilder To(This, getCurrentThisType(),
14982  /*IsArrow=*/true, MemberLookup);
14983 
14984  assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14985  "Member reference with rvalue base must be rvalue except for reference "
14986  "members, which aren't allowed for move assignment.");
14987 
14988  // Build the move of this field.
14989  StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14990  To, From,
14991  /*CopyingBaseSubobject=*/false,
14992  /*Copying=*/false);
14993  if (Move.isInvalid()) {
14994  MoveAssignOperator->setInvalidDecl();
14995  return;
14996  }
14997 
14998  // Success! Record the copy.
14999  Statements.push_back(Move.getAs<Stmt>());
15000  }
15001 
15002  if (!Invalid) {
15003  // Add a "return *this;"
15004  ExprResult ThisObj =
15005  CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
15006 
15007  StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
15008  if (Return.isInvalid())
15009  Invalid = true;
15010  else
15011  Statements.push_back(Return.getAs<Stmt>());
15012  }
15013 
15014  if (Invalid) {
15015  MoveAssignOperator->setInvalidDecl();
15016  return;
15017  }
15018 
15019  StmtResult Body;
15020  {
15021  CompoundScopeRAII CompoundScope(*this);
15022  Body = ActOnCompoundStmt(Loc, Loc, Statements,
15023  /*isStmtExpr=*/false);
15024  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15025  }
15026  MoveAssignOperator->setBody(Body.getAs<Stmt>());
15027  MoveAssignOperator->markUsed(Context);
15028 
15030  L->CompletedImplicitDefinition(MoveAssignOperator);
15031  }
15032 }
15033 
15035  CXXRecordDecl *ClassDecl) {
15036  // C++ [class.copy]p4:
15037  // If the class definition does not explicitly declare a copy
15038  // constructor, one is declared implicitly.
15039  assert(ClassDecl->needsImplicitCopyConstructor());
15040 
15041  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15042  if (DSM.isAlreadyBeingDeclared())
15043  return nullptr;
15044 
15045  QualType ClassType = Context.getTypeDeclType(ClassDecl);
15046  QualType ArgType = ClassType;
15047  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15048  if (Const)
15049  ArgType = ArgType.withConst();
15050 
15052  if (AS != LangAS::Default)
15053  ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15054 
15055  ArgType = Context.getLValueReferenceType(ArgType);
15056 
15057  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15059  Const);
15060 
15061  DeclarationName Name
15063  Context.getCanonicalType(ClassType));
15064  SourceLocation ClassLoc = ClassDecl->getLocation();
15065  DeclarationNameInfo NameInfo(Name, ClassLoc);
15066 
15067  // An implicitly-declared copy constructor is an inline public
15068  // member of its class.
15070  Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15071  ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15072  /*isInline=*/true,
15073  /*isImplicitlyDeclared=*/true,
15076  CopyConstructor->setAccess(AS_public);
15077  CopyConstructor->setDefaulted();
15078 
15079  if (getLangOpts().CUDA) {
15081  CopyConstructor,
15082  /* ConstRHS */ Const,
15083  /* Diagnose */ false);
15084  }
15085 
15086  setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15087 
15088  // During template instantiation of special member functions we need a
15089  // reliable TypeSourceInfo for the parameter types in order to allow functions
15090  // to be substituted.
15091  TypeSourceInfo *TSI = nullptr;
15092  if (inTemplateInstantiation() && ClassDecl->isLambda())
15093  TSI = Context.getTrivialTypeSourceInfo(ArgType);
15094 
15095  // Add the parameter to the constructor.
15096  ParmVarDecl *FromParam =
15097  ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15098  /*IdentifierInfo=*/nullptr, ArgType,
15099  /*TInfo=*/TSI, SC_None, nullptr);
15100  CopyConstructor->setParams(FromParam);
15101 
15102  CopyConstructor->setTrivial(
15104  ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15105  : ClassDecl->hasTrivialCopyConstructor());
15106 
15107  CopyConstructor->setTrivialForCall(
15108  ClassDecl->hasAttr<TrivialABIAttr>() ||
15110  ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15112  : ClassDecl->hasTrivialCopyConstructorForCall()));
15113 
15114  // Note that we have declared this constructor.
15116 
15117  Scope *S = getScopeForContext(ClassDecl);
15118  CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15119 
15120  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15122  SetDeclDeleted(CopyConstructor, ClassLoc);
15123  }
15124 
15125  if (S)
15126  PushOnScopeChains(CopyConstructor, S, false);
15127  ClassDecl->addDecl(CopyConstructor);
15128 
15129  return CopyConstructor;
15130 }
15131 
15133  CXXConstructorDecl *CopyConstructor) {
15134  assert((CopyConstructor->isDefaulted() &&
15135  CopyConstructor->isCopyConstructor() &&
15136  !CopyConstructor->doesThisDeclarationHaveABody() &&
15137  !CopyConstructor->isDeleted()) &&
15138  "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15139  if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15140  return;
15141 
15142  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15143  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15144 
15145  SynthesizedFunctionScope Scope(*this, CopyConstructor);
15146 
15147  // The exception specification is needed because we are defining the
15148  // function.
15149  ResolveExceptionSpec(CurrentLocation,
15150  CopyConstructor->getType()->castAs<FunctionProtoType>());
15151  MarkVTableUsed(CurrentLocation, ClassDecl);
15152 
15153  // Add a context note for diagnostics produced after this point.
15154  Scope.addContextNote(CurrentLocation);
15155 
15156  // C++11 [class.copy]p7:
15157  // The [definition of an implicitly declared copy constructor] is
15158  // deprecated if the class has a user-declared copy assignment operator
15159  // or a user-declared destructor.
15160  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15161  diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15162 
15163  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15164  CopyConstructor->setInvalidDecl();
15165  } else {
15166  SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15167  ? CopyConstructor->getEndLoc()
15168  : CopyConstructor->getLocation();
15169  Sema::CompoundScopeRAII CompoundScope(*this);
15170  CopyConstructor->setBody(
15171  ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15172  CopyConstructor->markUsed(Context);
15173  }
15174 
15176  L->CompletedImplicitDefinition(CopyConstructor);
15177  }
15178 }
15179 
15181  CXXRecordDecl *ClassDecl) {
15182  assert(ClassDecl->needsImplicitMoveConstructor());
15183 
15184  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15185  if (DSM.isAlreadyBeingDeclared())
15186  return nullptr;
15187 
15188  QualType ClassType = Context.getTypeDeclType(ClassDecl);
15189 
15190  QualType ArgType = ClassType;
15192  if (AS != LangAS::Default)
15193  ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15194  ArgType = Context.getRValueReferenceType(ArgType);
15195 
15196  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15198  false);
15199 
15200  DeclarationName Name
15202  Context.getCanonicalType(ClassType));
15203  SourceLocation ClassLoc = ClassDecl->getLocation();
15204  DeclarationNameInfo NameInfo(Name, ClassLoc);
15205 
15206  // C++11 [class.copy]p11:
15207  // An implicitly-declared copy/move constructor is an inline public
15208  // member of its class.
15210  Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15211  ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15212  /*isInline=*/true,
15213  /*isImplicitlyDeclared=*/true,
15216  MoveConstructor->setAccess(AS_public);
15217  MoveConstructor->setDefaulted();
15218 
15219  if (getLangOpts().CUDA) {
15221  MoveConstructor,
15222  /* ConstRHS */ false,
15223  /* Diagnose */ false);
15224  }
15225 
15226  setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15227 
15228  // Add the parameter to the constructor.
15229  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15230  ClassLoc, ClassLoc,
15231  /*IdentifierInfo=*/nullptr,
15232  ArgType, /*TInfo=*/nullptr,
15233  SC_None, nullptr);
15234  MoveConstructor->setParams(FromParam);
15235 
15236  MoveConstructor->setTrivial(
15238  ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15239  : ClassDecl->hasTrivialMoveConstructor());
15240 
15241  MoveConstructor->setTrivialForCall(
15242  ClassDecl->hasAttr<TrivialABIAttr>() ||
15244  ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15246  : ClassDecl->hasTrivialMoveConstructorForCall()));
15247 
15248  // Note that we have declared this constructor.
15250 
15251  Scope *S = getScopeForContext(ClassDecl);
15252  CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15253 
15254  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15256  SetDeclDeleted(MoveConstructor, ClassLoc);
15257  }
15258 
15259  if (S)
15260  PushOnScopeChains(MoveConstructor, S, false);
15261  ClassDecl->addDecl(MoveConstructor);
15262 
15263  return MoveConstructor;
15264 }
15265 
15267  CXXConstructorDecl *MoveConstructor) {
15268  assert((MoveConstructor->isDefaulted() &&
15269  MoveConstructor->isMoveConstructor() &&
15270  !MoveConstructor->doesThisDeclarationHaveABody() &&
15271  !MoveConstructor->isDeleted()) &&
15272  "DefineImplicitMoveConstructor - call it for implicit move ctor");
15273  if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15274  return;
15275 
15276  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15277  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15278 
15279  SynthesizedFunctionScope Scope(*this, MoveConstructor);
15280 
15281  // The exception specification is needed because we are defining the
15282  // function.
15283  ResolveExceptionSpec(CurrentLocation,
15284  MoveConstructor->getType()->castAs<FunctionProtoType>());
15285  MarkVTableUsed(CurrentLocation, ClassDecl);
15286 
15287  // Add a context note for diagnostics produced after this point.
15288  Scope.addContextNote(CurrentLocation);
15289 
15290  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15291  MoveConstructor->setInvalidDecl();
15292  } else {
15293  SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15294  ? MoveConstructor->getEndLoc()
15295  : MoveConstructor->getLocation();
15296  Sema::CompoundScopeRAII CompoundScope(*this);
15297  MoveConstructor->setBody(ActOnCompoundStmt(
15298  Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15299  MoveConstructor->markUsed(Context);
15300  }
15301 
15303  L->CompletedImplicitDefinition(MoveConstructor);
15304  }
15305 }
15306 
15308  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15309 }
15310 
15312  SourceLocation CurrentLocation,
15313  CXXConversionDecl *Conv) {
15314  SynthesizedFunctionScope Scope(*this, Conv);
15315  assert(!Conv->getReturnType()->isUndeducedType());
15316 
15317  QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15318  CallingConv CC =
15319  ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15320 
15321  CXXRecordDecl *Lambda = Conv->getParent();
15322  FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15323  FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15324 
15325  if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15327  CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15328  if (!CallOp)
15329  return;
15330 
15332  Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15333  if (!Invoker)
15334  return;
15335  }
15336 
15337  if (CallOp->isInvalidDecl())
15338  return;
15339 
15340  // Mark the call operator referenced (and add to pending instantiations
15341  // if necessary).
15342  // For both the conversion and static-invoker template specializations
15343  // we construct their body's in this function, so no need to add them
15344  // to the PendingInstantiations.
15345  MarkFunctionReferenced(CurrentLocation, CallOp);
15346 
15347  // Fill in the __invoke function with a dummy implementation. IR generation
15348  // will fill in the actual details. Update its type in case it contained
15349  // an 'auto'.
15350  Invoker->markUsed(Context);
15351  Invoker->setReferenced();
15352  Invoker->setType(Conv->getReturnType()->getPointeeType());
15353  Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15354 
15355  // Construct the body of the conversion function { return __invoke; }.
15356  Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15357  VK_LValue, Conv->getLocation());
15358  assert(FunctionRef && "Can't refer to __invoke function?");
15359  Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15360  Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15361  Conv->getLocation()));
15362  Conv->markUsed(Context);
15363  Conv->setReferenced();
15364 
15366  L->CompletedImplicitDefinition(Conv);
15367  L->CompletedImplicitDefinition(Invoker);
15368  }
15369 }
15370 
15371 
15372 
15374  SourceLocation CurrentLocation,
15375  CXXConversionDecl *Conv)
15376 {
15377  assert(!Conv->getParent()->isGenericLambda());
15378 
15379  SynthesizedFunctionScope Scope(*this, Conv);
15380 
15381  // Copy-initialize the lambda object as needed to capture it.
15382  Expr *This = ActOnCXXThis(CurrentLocation).get();
15383  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15384 
15385  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15386  Conv->getLocation(),
15387  Conv, DerefThis);
15388 
15389  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15390  // behavior. Note that only the general conversion function does this
15391  // (since it's unusable otherwise); in the case where we inline the
15392  // block literal, it has block literal lifetime semantics.
15393  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15394  BuildBlock = ImplicitCastExpr::Create(
15395  Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15396  BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15397 
15398  if (BuildBlock.isInvalid()) {
15399  Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15400  Conv->setInvalidDecl();
15401  return;
15402  }
15403 
15404  // Create the return statement that returns the block from the conversion
15405  // function.
15406  StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15407  if (Return.isInvalid()) {
15408  Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15409  Conv->setInvalidDecl();
15410  return;
15411  }
15412 
15413  // Set the body of the conversion function.
15414  Stmt *ReturnS = Return.get();
15415  Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15416  Conv->getLocation()));
15417  Conv->markUsed(Context);
15418 
15419  // We're done; notify the mutation listener, if any.
15421  L->CompletedImplicitDefinition(Conv);
15422  }
15423 }
15424 
15425 /// Determine whether the given list arguments contains exactly one
15426 /// "real" (non-default) argument.
15428  switch (Args.size()) {
15429  case 0:
15430  return false;
15431 
15432  default:
15433  if (!Args[1]->isDefaultArgument())
15434  return false;
15435 
15436  LLVM_FALLTHROUGH;
15437  case 1:
15438  return !Args[0]->isDefaultArgument();
15439  }
15440 
15441  return false;
15442 }
15443 
15444 ExprResult
15446  NamedDecl *FoundDecl,
15447  CXXConstructorDecl *Constructor,
15448  MultiExprArg ExprArgs,
15449  bool HadMultipleCandidates,
15450  bool IsListInitialization,
15451  bool IsStdInitListInitialization,
15452  bool RequiresZeroInit,
15453  unsigned ConstructKind,
15454  SourceRange ParenRange) {
15455  bool Elidable = false;
15456 
15457  // C++0x [class.copy]p34:
15458  // When certain criteria are met, an implementation is allowed to
15459  // omit the copy/move construction of a class object, even if the
15460  // copy/move constructor and/or destructor for the object have
15461  // side effects. [...]
15462  // - when a temporary class object that has not been bound to a
15463  // reference (12.2) would be copied/moved to a class object
15464  // with the same cv-unqualified type, the copy/move operation
15465  // can be omitted by constructing the temporary object
15466  // directly into the target of the omitted copy/move
15467  if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15468  // FIXME: Converting constructors should also be accepted.
15469  // But to fix this, the logic that digs down into a CXXConstructExpr
15470  // to find the source object needs to handle it.
15471  // Right now it assumes the source object is passed directly as the
15472  // first argument.
15473  Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15474  Expr *SubExpr = ExprArgs[0];
15475  // FIXME: Per above, this is also incorrect if we want to accept
15476  // converting constructors, as isTemporaryObject will
15477  // reject temporaries with different type from the
15478  // CXXRecord itself.
15479  Elidable = SubExpr->isTemporaryObject(
15480  Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15481  }
15482 
15483  return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15484  FoundDecl, Constructor,
15485  Elidable, ExprArgs, HadMultipleCandidates,
15486  IsListInitialization,
15487  IsStdInitListInitialization, RequiresZeroInit,
15488  ConstructKind, ParenRange);
15489 }
15490 
15491 ExprResult
15493  NamedDecl *FoundDecl,
15494  CXXConstructorDecl *Constructor,
15495  bool Elidable,
15496  MultiExprArg ExprArgs,
15497  bool HadMultipleCandidates,
15498  bool IsListInitialization,
15499  bool IsStdInitListInitialization,
15500  bool RequiresZeroInit,
15501  unsigned ConstructKind,
15502  SourceRange ParenRange) {
15503  if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15504  Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15505  if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15506  return ExprError();
15507  }
15508 
15509  return BuildCXXConstructExpr(
15510  ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15511  HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15512  RequiresZeroInit, ConstructKind, ParenRange);
15513 }
15514 
15515 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15516 /// including handling of its default argument expressions.
15517 ExprResult
15519  CXXConstructorDecl *Constructor,
15520  bool Elidable,
15521  MultiExprArg ExprArgs,
15522  bool HadMultipleCandidates,
15523  bool IsListInitialization,
15524  bool IsStdInitListInitialization,
15525  bool RequiresZeroInit,
15526  unsigned ConstructKind,
15527  SourceRange ParenRange) {
15528  assert(declaresSameEntity(
15529  Constructor->getParent(),
15530  DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15531  "given constructor for wrong type");
15532  MarkFunctionReferenced(ConstructLoc, Constructor);
15533  if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15534  return ExprError();
15535  if (getLangOpts().SYCLIsDevice &&
15536  !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15537  return ExprError();
15538 
15541  Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15542  HadMultipleCandidates, IsListInitialization,
15543  IsStdInitListInitialization, RequiresZeroInit,
15544  static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15545  ParenRange),
15546  Constructor);
15547 }
15548 
15550  assert(Field->hasInClassInitializer());
15551 
15552  // If we already have the in-class initializer nothing needs to be done.
15553  if (Field->getInClassInitializer())
15554  return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15555 
15556  // If we might have already tried and failed to instantiate, don't try again.
15557  if (Field->isInvalidDecl())
15558  return ExprError();
15559 
15560  // Maybe we haven't instantiated the in-class initializer. Go check the
15561  // pattern FieldDecl to see if it has one.
15562  CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15563 
15565  CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15567  ClassPattern->lookup(Field->getDeclName());
15568 
15569  FieldDecl *Pattern = nullptr;
15570  for (auto L : Lookup) {
15571  if (isa<FieldDecl>(L)) {
15572  Pattern = cast<FieldDecl>(L);
15573  break;
15574  }
15575  }
15576  assert(Pattern && "We must have set the Pattern!");
15577 
15578  if (!Pattern->hasInClassInitializer() ||
15579  InstantiateInClassInitializer(Loc, Field, Pattern,
15580  getTemplateInstantiationArgs(Field))) {
15581  // Don't diagnose this again.
15582  Field->setInvalidDecl();
15583  return ExprError();
15584  }
15585  return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15586  }
15587 
15588  // DR1351:
15589  // If the brace-or-equal-initializer of a non-static data member
15590  // invokes a defaulted default constructor of its class or of an
15591  // enclosing class in a potentially evaluated subexpression, the
15592  // program is ill-formed.
15593  //
15594  // This resolution is unworkable: the exception specification of the
15595  // default constructor can be needed in an unevaluated context, in
15596  // particular, in the operand of a noexcept-expression, and we can be
15597  // unable to compute an exception specification for an enclosed class.
15598  //
15599  // Any attempt to resolve the exception specification of a defaulted default
15600  // constructor before the initializer is lexically complete will ultimately
15601  // come here at which point we can diagnose it.
15602  RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15603  Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15604  << OutermostClass << Field;
15605  Diag(Field->getEndLoc(),
15606  diag::note_default_member_initializer_not_yet_parsed);
15607  // Recover by marking the field invalid, unless we're in a SFINAE context.
15608  if (!isSFINAEContext())
15609  Field->setInvalidDecl();
15610  return ExprError();
15611 }
15612 
15614  if (VD->isInvalidDecl()) return;
15615  // If initializing the variable failed, don't also diagnose problems with
15616  // the destructor, they're likely related.
15617  if (VD->getInit() && VD->getInit()->containsErrors())
15618  return;
15619 
15620  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15621  if (ClassDecl->isInvalidDecl()) return;
15622  if (ClassDecl->hasIrrelevantDestructor()) return;
15623  if (ClassDecl->isDependentContext()) return;
15624 
15625  if (VD->isNoDestroy(getASTContext()))
15626  return;
15627 
15628  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15629 
15630  // If this is an array, we'll require the destructor during initialization, so
15631  // we can skip over this. We still want to emit exit-time destructor warnings
15632  // though.
15633  if (!VD->getType()->isArrayType()) {
15634  MarkFunctionReferenced(VD->getLocation(), Destructor);
15635  CheckDestructorAccess(VD->getLocation(), Destructor,
15636  PDiag(diag::err_access_dtor_var)
15637  << VD->getDeclName() << VD->getType());
15638  DiagnoseUseOfDecl(Destructor, VD->getLocation());
15639  }
15640 
15641  if (Destructor->isTrivial()) return;
15642 
15643  // If the destructor is constexpr, check whether the variable has constant
15644  // destruction now.
15645  if (Destructor->isConstexpr()) {
15646  bool HasConstantInit = false;
15647  if (VD->getInit() && !VD->getInit()->isValueDependent())
15648  HasConstantInit = VD->evaluateValue();
15650  if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15651  HasConstantInit) {
15652  Diag(VD->getLocation(),
15653  diag::err_constexpr_var_requires_const_destruction) << VD;
15654  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15655  Diag(Notes[I].first, Notes[I].second);
15656  }
15657  }
15658 
15659  if (!VD->hasGlobalStorage()) return;
15660 
15661  // Emit warning for non-trivial dtor in global scope (a real global,
15662  // class-static, function-static).
15663  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15664 
15665  // TODO: this should be re-enabled for static locals by !CXAAtExit
15666  if (!VD->isStaticLocal())
15667  Diag(VD->getLocation(), diag::warn_global_destructor);
15668 }
15669 
15670 /// Given a constructor and the set of arguments provided for the
15671 /// constructor, convert the arguments and add any required default arguments
15672 /// to form a proper call to this constructor.
15673 ///
15674 /// \returns true if an error occurred, false otherwise.
15676  QualType DeclInitType, MultiExprArg ArgsPtr,
15677  SourceLocation Loc,
15678  SmallVectorImpl<Expr *> &ConvertedArgs,
15679  bool AllowExplicit,
15680  bool IsListInitialization) {
15681  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15682  unsigned NumArgs = ArgsPtr.size();
15683  Expr **Args = ArgsPtr.data();
15684 
15685  const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15686  unsigned NumParams = Proto->getNumParams();
15687 
15688  // If too few arguments are available, we'll fill in the rest with defaults.
15689  if (NumArgs < NumParams)
15690  ConvertedArgs.reserve(NumParams);
15691  else
15692  ConvertedArgs.reserve(NumArgs);
15693 
15694  VariadicCallType CallType =
15695  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15696  SmallVector<Expr *, 8> AllArgs;
15697  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15698  Proto, 0,
15699  llvm::makeArrayRef(Args, NumArgs),
15700  AllArgs,
15701  CallType, AllowExplicit,
15702  IsListInitialization);
15703  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15704 
15705  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15706 
15707  CheckConstructorCall(Constructor, DeclInitType,
15708  llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15709  Proto, Loc);
15710 
15711  return Invalid;
15712 }
15713 
15714 static inline bool
15716  const FunctionDecl *FnDecl) {
15717  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15718  if (isa<NamespaceDecl>(DC)) {
15719  return SemaRef.Diag(FnDecl->getLocation(),
15720  diag::err_operator_new_delete_declared_in_namespace)
15721  << FnDecl->getDeclName();
15722  }
15723 
15724  if (isa<TranslationUnitDecl>(DC) &&
15725  FnDecl->getStorageClass() == SC_Static) {
15726  return SemaRef.Diag(FnDecl->getLocation(),
15727  diag::err_operator_new_delete_declared_static)
15728  << FnDecl->getDeclName();
15729  }
15730 
15731  return false;
15732 }
15733 
15735  const PointerType *PtrTy) {
15736  auto &Ctx = SemaRef.Context;
15737  Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15738  PtrQuals.removeAddressSpace();
15739  return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15740  PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15741 }
15742 
15743 static inline bool
15745  CanQualType ExpectedResultType,
15746  CanQualType ExpectedFirstParamType,
15747  unsigned DependentParamTypeDiag,
15748  unsigned InvalidParamTypeDiag) {
15749  QualType ResultType =
15750  FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15751 
15752  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15753  // The operator is valid on any address space for OpenCL.
15754  // Drop address space from actual and expected result types.
15755  if (const auto *PtrTy = ResultType->getAs<PointerType>())
15756  ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15757 
15758  if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15759  ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15760  }
15761 
15762  // Check that the result type is what we expect.
15763  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15764  // Reject even if the type is dependent; an operator delete function is
15765  // required to have a non-dependent result type.
15766  return SemaRef.Diag(
15767  FnDecl->getLocation(),
15768  ResultType->isDependentType()
15769  ? diag::err_operator_new_delete_dependent_result_type
15770  : diag::err_operator_new_delete_invalid_result_type)
15771  << FnDecl->getDeclName() << ExpectedResultType;
15772  }
15773 
15774  // A function template must have at least 2 parameters.
15775  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15776  return SemaRef.Diag(FnDecl->getLocation(),
15777  diag::err_operator_new_delete_template_too_few_parameters)
15778  << FnDecl->getDeclName();
15779 
15780  // The function decl must have at least 1 parameter.
15781  if (FnDecl->getNumParams() == 0)
15782  return SemaRef.Diag(FnDecl->getLocation(),
15783  diag::err_operator_new_delete_too_few_parameters)
15784  << FnDecl->getDeclName();
15785 
15786  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15787  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15788  // The operator is valid on any address space for OpenCL.
15789  // Drop address space from actual and expected first parameter types.
15790  if (const auto *PtrTy =
15791  FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15792  FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15793 
15794  if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15795  ExpectedFirstParamType =
15796  RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15797  }
15798 
15799  // Check that the first parameter type is what we expect.
15800  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15801  ExpectedFirstParamType) {
15802  // The first parameter type is not allowed to be dependent. As a tentative
15803  // DR resolution, we allow a dependent parameter type if it is the right
15804  // type anyway, to allow destroying operator delete in class templates.
15805  return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15806  ? DependentParamTypeDiag
15807  : InvalidParamTypeDiag)
15808  << FnDecl->getDeclName() << ExpectedFirstParamType;
15809  }
15810 
15811  return false;
15812 }
15813 
15814 static bool
15816  // C++ [basic.stc.dynamic.allocation]p1:
15817  // A program is ill-formed if an allocation function is declared in a
15818  // namespace scope other than global scope or declared static in global
15819  // scope.
15820  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15821  return true;
15822 
15823  CanQualType SizeTy =
15824  SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15825 
15826  // C++ [basic.stc.dynamic.allocation]p1:
15827  // The return type shall be void*. The first parameter shall have type
15828  // std::size_t.
15829  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15830  SizeTy,
15831  diag::err_operator_new_dependent_param_type,
15832  diag::err_operator_new_param_type))
15833  return true;
15834 
15835  // C++ [basic.stc.dynamic.allocation]p1:
15836  // The first parameter shall not have an associated default argument.
15837  if (FnDecl->getParamDecl(0)->hasDefaultArg())
15838  return SemaRef.Diag(FnDecl->getLocation(),
15839  diag::err_operator_new_default_arg)
15840  << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15841 
15842  return false;
15843 }
15844 
15845 static bool
15847  // C++ [basic.stc.dynamic.deallocation]p1:
15848  // A program is ill-formed if deallocation functions are declared in a
15849  // namespace scope other than global scope or declared static in global
15850  // scope.
15851  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15852  return true;
15853 
15854  auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15855 
15856  // C++ P0722:
15857  // Within a class C, the first parameter of a destroying operator delete
15858  // shall be of type C *. The first parameter of any other deallocation
15859  // function shall be of type void *.
15860  CanQualType ExpectedFirstParamType =
15861  MD && MD->isDestroyingOperatorDelete()
15862  ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15863  SemaRef.Context.getRecordType(MD->getParent())))
15864  : SemaRef.Context.VoidPtrTy;
15865 
15866  // C++ [basic.stc.dynamic.deallocation]p2:
15867  // Each deallocation function shall return void
15869  SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15870  diag::err_operator_delete_dependent_param_type,
15871  diag::err_operator_delete_param_type))
15872  return true;
15873 
15874  // C++ P0722:
15875  // A destroying operator delete shall be a usual deallocation function.
15876  if (MD && !MD->getParent()->isDependentContext() &&
15878  !SemaRef.isUsualDeallocationFunction(MD)) {
15879  SemaRef.Diag(MD->getLocation(),
15880  diag::err_destroying_operator_delete_not_usual);
15881  return true;
15882  }
15883 
15884  return false;
15885 }
15886 
15887 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15888 /// of this overloaded operator is well-formed. If so, returns false;
15889 /// otherwise, emits appropriate diagnostics and returns true.
15891  assert(FnDecl && FnDecl->isOverloadedOperator() &&
15892  "Expected an overloaded operator declaration");
15893 
15895 
15896  // C++ [over.oper]p5:
15897  // The allocation and deallocation functions, operator new,
15898  // operator new[], operator delete and operator delete[], are
15899  // described completely in 3.7.3. The attributes and restrictions
15900  // found in the rest of this subclause do not apply to them unless
15901  // explicitly stated in 3.7.3.
15902  if (Op == OO_Delete || Op == OO_Array_Delete)
15903  return CheckOperatorDeleteDeclaration(*this, FnDecl);
15904 
15905  if (Op == OO_New || Op == OO_Array_New)
15906  return CheckOperatorNewDeclaration(*this, FnDecl);
15907 
15908  // C++ [over.oper]p6:
15909  // An operator function shall either be a non-static member
15910  // function or be a non-member function and have at least one
15911  // parameter whose type is a class, a reference to a class, an
15912  // enumeration, or a reference to an enumeration.
15913  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15914  if (MethodDecl->isStatic())
15915  return Diag(FnDecl->getLocation(),
15916  diag::err_operator_overload_static) << FnDecl->getDeclName();
15917  } else {
15918  bool ClassOrEnumParam = false;
15919  for (auto Param : FnDecl->parameters()) {
15920  QualType ParamType = Param->getType().getNonReferenceType();
15921  if (ParamType->isDependentType() || ParamType->isRecordType() ||
15922  ParamType->isEnumeralType()) {
15923  ClassOrEnumParam = true;
15924  break;
15925  }
15926  }
15927 
15928  if (!ClassOrEnumParam)
15929  return Diag(FnDecl->getLocation(),
15930  diag::err_operator_overload_needs_class_or_enum)
15931  << FnDecl->getDeclName();
15932  }
15933 
15934  // C++ [over.oper]p8:
15935  // An operator function cannot have default arguments (8.3.6),
15936  // except where explicitly stated below.
15937  //
15938  // Only the function-call operator (C++ [over.call]p1) and the subscript
15939  // operator (CWG2507) allow default arguments.
15940  if (Op != OO_Call) {
15941  ParmVarDecl *FirstDefaultedParam = nullptr;
15942  for (auto Param : FnDecl->parameters()) {
15943  if (Param->hasDefaultArg()) {
15944  FirstDefaultedParam = Param;
15945  break;
15946  }
15947  }
15948  if (FirstDefaultedParam) {
15949  if (Op == OO_Subscript) {
15950  Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15951  ? diag::ext_subscript_overload
15952  : diag::error_subscript_overload)
15953  << FnDecl->getDeclName() << 1
15954  << FirstDefaultedParam->getDefaultArgRange();
15955  } else {
15956  return Diag(FirstDefaultedParam->getLocation(),
15957  diag::err_operator_overload_default_arg)
15958  << FnDecl->getDeclName()
15959  << FirstDefaultedParam->getDefaultArgRange();
15960  }
15961  }
15962  }
15963 
15964  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15965  { false, false, false }
15966 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15967  , { Unary, Binary, MemberOnly }
15968 #include "clang/Basic/OperatorKinds.def"
15969  };
15970 
15971  bool CanBeUnaryOperator = OperatorUses[Op][0];
15972  bool CanBeBinaryOperator = OperatorUses[Op][1];
15973  bool MustBeMemberOperator = OperatorUses[Op][2];
15974 
15975  // C++ [over.oper]p8:
15976  // [...] Operator functions cannot have more or fewer parameters
15977  // than the number required for the corresponding operator, as
15978  // described in the rest of this subclause.
15979  unsigned NumParams = FnDecl->getNumParams()
15980  + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15981  if (Op != OO_Call && Op != OO_Subscript &&
15982  ((NumParams == 1 && !CanBeUnaryOperator) ||
15983  (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15984  (NumParams > 2))) {
15985  // We have the wrong number of parameters.
15986  unsigned ErrorKind;
15987  if (CanBeUnaryOperator && CanBeBinaryOperator) {
15988  ErrorKind = 2; // 2 -> unary or binary.
15989  } else if (CanBeUnaryOperator) {
15990  ErrorKind = 0; // 0 -> unary
15991  } else {
15992  assert(CanBeBinaryOperator &&
15993  "All non-call overloaded operators are unary or binary!");
15994  ErrorKind = 1; // 1 -> binary
15995  }
15996  return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15997  << FnDecl->getDeclName() << NumParams << ErrorKind;
15998  }
15999 
16000  if (Op == OO_Subscript && NumParams != 2) {
16001  Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
16002  ? diag::ext_subscript_overload
16003  : diag::error_subscript_overload)
16004  << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16005  }
16006 
16007  // Overloaded operators other than operator() and operator[] cannot be
16008  // variadic.
16009  if (Op != OO_Call &&
16010  FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16011  return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16012  << FnDecl->getDeclName();
16013  }
16014 
16015  // Some operators must be non-static member functions.
16016  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16017  return Diag(FnDecl->getLocation(),
16018  diag::err_operator_overload_must_be_member)
16019  << FnDecl->getDeclName();
16020  }
16021 
16022  // C++ [over.inc]p1:
16023  // The user-defined function called operator++ implements the
16024  // prefix and postfix ++ operator. If this function is a member
16025  // function with no parameters, or a non-member function with one
16026  // parameter of class or enumeration type, it defines the prefix
16027  // increment operator ++ for objects of that type. If the function
16028  // is a member function with one parameter (which shall be of type
16029  // int) or a non-member function with two parameters (the second
16030  // of which shall be of type int), it defines the postfix
16031  // increment operator ++ for objects of that type.
16032  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16033  ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16034  QualType ParamType = LastParam->getType();
16035 
16036  if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16037  !ParamType->isDependentType())
16038  return Diag(LastParam->getLocation(),
16039  diag::err_operator_overload_post_incdec_must_be_int)
16040  << LastParam->getType() << (Op == OO_MinusMinus);
16041  }
16042 
16043  return false;
16044 }
16045 
16046 static bool
16048  FunctionTemplateDecl *TpDecl) {
16049  TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16050 
16051  // Must have one or two template parameters.
16052  if (TemplateParams->size() == 1) {
16053  NonTypeTemplateParmDecl *PmDecl =
16054  dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16055 
16056  // The template parameter must be a char parameter pack.
16057  if (PmDecl && PmDecl->isTemplateParameterPack() &&
16058  SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16059  return false;
16060 
16061  // C++20 [over.literal]p5:
16062  // A string literal operator template is a literal operator template
16063  // whose template-parameter-list comprises a single non-type
16064  // template-parameter of class type.
16065  //
16066  // As a DR resolution, we also allow placeholders for deduced class
16067  // template specializations.
16068  if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16069  !PmDecl->isTemplateParameterPack() &&
16070  (PmDecl->getType()->isRecordType() ||
16072  return false;
16073  } else if (TemplateParams->size() == 2) {
16074  TemplateTypeParmDecl *PmType =
16075  dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16076  NonTypeTemplateParmDecl *PmArgs =
16077  dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16078 
16079  // The second template parameter must be a parameter pack with the
16080  // first template parameter as its type.
16081  if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16082  PmArgs->isTemplateParameterPack()) {
16083  const TemplateTypeParmType *TArgs =
16084  PmArgs->getType()->getAs<TemplateTypeParmType>();
16085  if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16086  TArgs->getIndex() == PmType->getIndex()) {
16087  if (!SemaRef.inTemplateInstantiation())
16088  SemaRef.Diag(TpDecl->getLocation(),
16089  diag::ext_string_literal_operator_template);
16090  return false;
16091  }
16092  }
16093  }
16094 
16095  SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16096  diag::err_literal_operator_template)
16097  << TpDecl->getTemplateParameters()->getSourceRange();
16098  return true;
16099 }
16100 
16101 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16102 /// of this literal operator function is well-formed. If so, returns
16103 /// false; otherwise, emits appropriate diagnostics and returns true.
16105  if (isa<CXXMethodDecl>(FnDecl)) {
16106  Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16107  << FnDecl->getDeclName();
16108  return true;
16109  }
16110 
16111  if (FnDecl->isExternC()) {
16112  Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16113  if (const LinkageSpecDecl *LSD =
16114  FnDecl->getDeclContext()->getExternCContext())
16115  Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16116  return true;
16117  }
16118 
16119  // This might be the definition of a literal operator template.
16121 
16122  // This might be a specialization of a literal operator template.
16123  if (!TpDecl)
16124  TpDecl = FnDecl->getPrimaryTemplate();
16125 
16126  // template <char...> type operator "" name() and
16127  // template <class T, T...> type operator "" name() are the only valid
16128  // template signatures, and the only valid signatures with no parameters.
16129  //
16130  // C++20 also allows template <SomeClass T> type operator "" name().
16131  if (TpDecl) {
16132  if (FnDecl->param_size() != 0) {
16133  Diag(FnDecl->getLocation(),
16134  diag::err_literal_operator_template_with_params);
16135  return true;
16136  }
16137 
16138  if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16139  return true;
16140 
16141  } else if (FnDecl->param_size() == 1) {
16142  const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16143 
16144  QualType ParamType = Param->getType().getUnqualifiedType();
16145 
16146  // Only unsigned long long int, long double, any character type, and const
16147  // char * are allowed as the only parameters.
16148  if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16149  ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16150  Context.hasSameType(ParamType, Context.CharTy) ||
16151  Context.hasSameType(ParamType, Context.WideCharTy) ||
16152  Context.hasSameType(ParamType, Context.Char8Ty) ||
16153  Context.hasSameType(ParamType, Context.Char16Ty) ||
16154  Context.hasSameType(ParamType, Context.Char32Ty)) {
16155  } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16156  QualType InnerType = Ptr->getPointeeType();
16157 
16158  // Pointer parameter must be a const char *.
16159  if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16160  Context.CharTy) &&
16161  InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16162  Diag(Param->getSourceRange().getBegin(),
16163  diag::err_literal_operator_param)
16164  << ParamType << "'const char *'" << Param->getSourceRange();
16165  return true;
16166  }
16167 
16168  } else if (ParamType->isRealFloatingType()) {
16169  Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16170  << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16171  return true;
16172 
16173  } else if (ParamType->isIntegerType()) {
16174  Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16175  << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16176  return true;
16177 
16178  } else {
16179  Diag(Param->getSourceRange().getBegin(),
16180  diag::err_literal_operator_invalid_param)
16181  << ParamType << Param->getSourceRange();
16182  return true;
16183  }
16184 
16185  } else if (FnDecl->param_size() == 2) {
16186  FunctionDecl::param_iterator Param = FnDecl->param_begin();
16187 
16188  // First, verify that the first parameter is correct.
16189 
16190  QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16191 
16192  // Two parameter function must have a pointer to const as a
16193  // first parameter; let's strip those qualifiers.
16194  const PointerType *PT = FirstParamType->getAs<PointerType>();
16195 
16196  if (!PT) {
16197  Diag((*Param)->getSourceRange().getBegin(),
16198  diag::err_literal_operator_param)
16199  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16200  return true;
16201  }
16202 
16203  QualType PointeeType = PT->getPointeeType();
16204  // First parameter must be const
16205  if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16206  Diag((*Param)->getSourceRange().getBegin(),
16207  diag::err_literal_operator_param)
16208  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16209  return true;
16210  }
16211 
16212  QualType InnerType = PointeeType.getUnqualifiedType();
16213  // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16214  // const char32_t* are allowed as the first parameter to a two-parameter
16215  // function
16216  if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16217  Context.hasSameType(InnerType, Context.WideCharTy) ||
16218  Context.hasSameType(InnerType, Context.Char8Ty) ||
16219  Context.hasSameType(InnerType, Context.Char16Ty) ||
16220  Context.hasSameType(InnerType, Context.Char32Ty))) {
16221  Diag((*Param)->getSourceRange().getBegin(),
16222  diag::err_literal_operator_param)
16223  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16224  return true;
16225  }
16226 
16227  // Move on to the second and final parameter.
16228  ++Param;
16229 
16230  // The second parameter must be a std::size_t.
16231  QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16232  if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16233  Diag((*Param)->getSourceRange().getBegin(),
16234  diag::err_literal_operator_param)
16235  << SecondParamType << Context.getSizeType()
16236  << (*Param)->getSourceRange();
16237  return true;
16238  }
16239  } else {
16240  Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16241  return true;
16242  }
16243 
16244  // Parameters are good.
16245 
16246  // A parameter-declaration-clause containing a default argument is not
16247  // equivalent to any of the permitted forms.
16248  for (auto Param : FnDecl->parameters()) {
16249  if (Param->hasDefaultArg()) {
16250  Diag(Param->getDefaultArgRange().getBegin(),
16251  diag::err_literal_operator_default_argument)
16252  << Param->getDefaultArgRange();
16253  break;
16254  }
16255  }
16256 
16257  StringRef LiteralName
16258  = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16259  if (LiteralName[0] != '_' &&
16260  !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16261  // C++11 [usrlit.suffix]p1:
16262  // Literal suffix identifiers that do not start with an underscore
16263  // are reserved for future standardization.
16264  Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16266  }
16267 
16268  return false;
16269 }
16270 
16271 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16272 /// linkage specification, including the language and (if present)
16273 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16274 /// language string literal. LBraceLoc, if valid, provides the location of
16275 /// the '{' brace. Otherwise, this linkage specification does not
16276 /// have any braces.
16278  Expr *LangStr,
16279  SourceLocation LBraceLoc) {
16280  StringLiteral *Lit = cast<StringLiteral>(LangStr);
16281  if (!Lit->isAscii()) {
16282  Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16283  << LangStr->getSourceRange();
16284  return nullptr;
16285  }
16286 
16287  StringRef Lang = Lit->getString();
16289  if (Lang == "C")
16291  else if (Lang == "C++")
16293  else {
16294  Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16295  << LangStr->getSourceRange();
16296  return nullptr;
16297  }
16298 
16299  // FIXME: Add all the various semantics of linkage specifications
16300 
16302  LangStr->getExprLoc(), Language,
16303  LBraceLoc.isValid());
16304 
16305  /// C++ [module.unit]p7.2.3
16306  /// - Otherwise, if the declaration
16307  /// - ...
16308  /// - ...
16309  /// - appears within a linkage-specification,
16310  /// it is attached to the global module.
16311  ///
16312  /// If the declaration is already in global module fragment, we don't
16313  /// need to attach it again.
16314  if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16315  Module *GlobalModule =
16316  PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16318  D->setLocalOwningModule(GlobalModule);
16319  }
16320 
16321  CurContext->addDecl(D);
16322  PushDeclContext(S, D);
16323  return D;
16324 }
16325 
16326 /// ActOnFinishLinkageSpecification - Complete the definition of
16327 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16328 /// valid, it's the position of the closing '}' brace in a linkage
16329 /// specification that uses braces.
16331  Decl *LinkageSpec,
16332  SourceLocation RBraceLoc) {
16333  if (RBraceLoc.isValid()) {
16334  LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16335  LSDecl->setRBraceLoc(RBraceLoc);
16336  }
16337 
16338  // If the current module doesn't has Parent, it implies that the
16339  // LinkageSpec isn't in the module created by itself. So we don't
16340  // need to pop it.
16341  if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16342  getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16343  PopGlobalModuleFragment();
16344 
16345  PopDeclContext();
16346  return LinkageSpec;
16347 }
16348 
16350  const ParsedAttributesView &AttrList,
16351  SourceLocation SemiLoc) {
16352  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16353  // Attribute declarations appertain to empty declaration so we handle
16354  // them here.
16355  ProcessDeclAttributeList(S, ED, AttrList);
16356 
16357  CurContext->addDecl(ED);
16358  return ED;
16359 }
16360 
16361 /// Perform semantic analysis for the variable declaration that
16362 /// occurs within a C++ catch clause, returning the newly-created
16363 /// variable.
16365  TypeSourceInfo *TInfo,
16366  SourceLocation StartLoc,
16367  SourceLocation Loc,
16368  IdentifierInfo *Name) {
16369  bool Invalid = false;
16370  QualType ExDeclType = TInfo->getType();
16371 
16372  // Arrays and functions decay.
16373  if (ExDeclType->isArrayType())
16374  ExDeclType = Context.getArrayDecayedType(ExDeclType);
16375  else if (ExDeclType->isFunctionType())
16376  ExDeclType = Context.getPointerType(ExDeclType);
16377 
16378  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16379  // The exception-declaration shall not denote a pointer or reference to an
16380  // incomplete type, other than [cv] void*.
16381  // N2844 forbids rvalue references.
16382  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16383  Diag(Loc, diag::err_catch_rvalue_ref);
16384  Invalid = true;
16385  }
16386 
16387  if (ExDeclType->isVariablyModifiedType()) {
16388  Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16389  Invalid = true;
16390  }
16391 
16392  QualType BaseType = ExDeclType;
16393  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16394  unsigned DK = diag::err_catch_incomplete;
16395  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16396  BaseType = Ptr->getPointeeType();
16397  Mode = 1;
16398  DK = diag::err_catch_incomplete_ptr;
16399  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16400  // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16401  BaseType = Ref->getPointeeType();
16402  Mode = 2;
16403  DK = diag::err_catch_incomplete_ref;
16404  }
16405  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16406  !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16407  Invalid = true;
16408 
16409  if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16410  Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16411  Invalid = true;
16412  }
16413 
16414  if (!Invalid && !ExDeclType->isDependentType() &&
16415  RequireNonAbstractType(Loc, ExDeclType,
16416  diag::err_abstract_type_in_decl,
16418  Invalid = true;
16419 
16420  // Only the non-fragile NeXT runtime currently supports C++ catches
16421  // of ObjC types, and no runtime supports catching ObjC types by value.
16422  if (!Invalid && getLangOpts().ObjC) {
16423  QualType T = ExDeclType;
16424  if (const ReferenceType *RT = T->getAs<ReferenceType>())
16425  T = RT->getPointeeType();
16426 
16427  if (T->isObjCObjectType()) {
16428  Diag(Loc, diag::err_objc_object_catch);
16429  Invalid = true;
16430  } else if (T->isObjCObjectPointerType()) {
16431  // FIXME: should this be a test for macosx-fragile specifically?
16433  Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16434  }
16435  }
16436 
16437  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16438  ExDeclType, TInfo, SC_None);
16439  ExDecl->setExceptionVariable(true);
16440 
16441  // In ARC, infer 'retaining' for variables of retainable type.
16442  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16443  Invalid = true;
16444 
16445  if (!Invalid && !ExDeclType->isDependentType()) {
16446  if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16447  // Insulate this from anything else we might currently be parsing.
16450 
16451  // C++ [except.handle]p16:
16452  // The object declared in an exception-declaration or, if the
16453  // exception-declaration does not specify a name, a temporary (12.2) is
16454  // copy-initialized (8.5) from the exception object. [...]
16455  // The object is destroyed when the handler exits, after the destruction
16456  // of any automatic objects initialized within the handler.
16457  //
16458  // We just pretend to initialize the object with itself, then make sure
16459  // it can be destroyed later.
16460  QualType initType = Context.getExceptionObjectType(ExDeclType);
16461 
16462  InitializedEntity entity =
16464  InitializationKind initKind =
16466 
16467  Expr *opaqueValue =
16468  new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16469  InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16470  ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16471  if (result.isInvalid())
16472  Invalid = true;
16473  else {
16474  // If the constructor used was non-trivial, set this as the
16475  // "initializer".
16476  CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16477  if (!construct->getConstructor()->isTrivial()) {
16478  Expr *init = MaybeCreateExprWithCleanups(construct);
16479  ExDecl->setInit(init);
16480  }
16481 
16482  // And make sure it's destructable.
16484  }
16485  }
16486  }
16487 
16488  if (Invalid)
16489  ExDecl->setInvalidDecl();
16490 
16491  return ExDecl;
16492 }
16493 
16494 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16495 /// handler.
16497  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16498  bool Invalid = D.isInvalidType();
16499 
16500  // Check for unexpanded parameter packs.
16502  UPPC_ExceptionType)) {
16504  D.getIdentifierLoc());
16505  Invalid = true;
16506  }
16507 
16508  IdentifierInfo *II = D.getIdentifier();
16509  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16512  // The scope should be freshly made just for us. There is just no way
16513  // it contains any previous declaration, except for function parameters in
16514  // a function-try-block's catch statement.
16515  assert(!S->isDeclScope(PrevDecl));
16516  if (isDeclInScope(PrevDecl, CurContext, S)) {
16517  Diag(D.getIdentifierLoc(), diag::err_redefinition)
16518  << D.getIdentifier();
16519  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16520  Invalid = true;
16521  } else if (PrevDecl->isTemplateParameter())
16522  // Maybe we will complain about the shadowed template parameter.
16524  }
16525 
16526  if (D.getCXXScopeSpec().isSet() && !Invalid) {
16527  Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16528  << D.getCXXScopeSpec().getRange();
16529  Invalid = true;
16530  }
16531 
16533  S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16534  if (Invalid)
16535  ExDecl->setInvalidDecl();
16536 
16537  // Add the exception declaration into this scope.
16538  if (II)
16539  PushOnScopeChains(ExDecl, S);
16540  else
16541  CurContext->addDecl(ExDecl);
16542 
16543  ProcessDeclAttributes(S, ExDecl, D);
16544  return ExDecl;
16545 }
16546 
16548  Expr *AssertExpr,
16549  Expr *AssertMessageExpr,
16550  SourceLocation RParenLoc) {
16551  StringLiteral *AssertMessage =
16552  AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16553 
16555  return nullptr;
16556 
16557  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16558  AssertMessage, RParenLoc, false);
16559 }
16560 
16562  Expr *AssertExpr,
16563  StringLiteral *AssertMessage,
16564  SourceLocation RParenLoc,
16565  bool Failed) {
16566  assert(AssertExpr != nullptr && "Expected non-null condition");
16567  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16568  !Failed) {
16569  // In a static_assert-declaration, the constant-expression shall be a
16570  // constant expression that can be contextually converted to bool.
16571  ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16572  if (Converted.isInvalid())
16573  Failed = true;
16574 
16575  ExprResult FullAssertExpr =
16576  ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16577  /*DiscardedValue*/ false,
16578  /*IsConstexpr*/ true);
16579  if (FullAssertExpr.isInvalid())
16580  Failed = true;
16581  else
16582  AssertExpr = FullAssertExpr.get();
16583 
16584  llvm::APSInt Cond;
16585  if (!Failed && VerifyIntegerConstantExpression(
16586  AssertExpr, &Cond,
16587  diag::err_static_assert_expression_is_not_constant)
16588  .isInvalid())
16589  Failed = true;
16590 
16591  if (!Failed && !Cond) {
16592  SmallString<256> MsgBuffer;
16593  llvm::raw_svector_ostream Msg(MsgBuffer);
16594  if (AssertMessage)
16595  AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16596 
16597  Expr *InnerCond = nullptr;
16598  std::string InnerCondDescription;
16599  std::tie(InnerCond, InnerCondDescription) =
16600  findFailedBooleanCondition(Converted.get());
16601  if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16602  // Drill down into concept specialization expressions to see why they
16603  // weren't satisfied.
16604  Diag(StaticAssertLoc, diag::err_static_assert_failed)
16605  << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16606  ConstraintSatisfaction Satisfaction;
16607  if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16608  DiagnoseUnsatisfiedConstraint(Satisfaction);
16609  } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16610  && !isa<IntegerLiteral>(InnerCond)) {
16611  Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16612  << InnerCondDescription << !AssertMessage
16613  << Msg.str() << InnerCond->getSourceRange();
16614  } else {
16615  Diag(StaticAssertLoc, diag::err_static_assert_failed)
16616  << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16617  }
16618  Failed = true;
16619  }
16620  } else {
16621  ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16622  /*DiscardedValue*/false,
16623  /*IsConstexpr*/true);
16624  if (FullAssertExpr.isInvalid())
16625  Failed = true;
16626  else
16627  AssertExpr = FullAssertExpr.get();
16628  }
16629 
16630  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16631  AssertExpr, AssertMessage, RParenLoc,
16632  Failed);
16633 
16635  return Decl;
16636 }
16637 
16638 /// Perform semantic analysis of the given friend type declaration.
16639 ///
16640 /// \returns A friend declaration that.
16642  SourceLocation FriendLoc,
16643  TypeSourceInfo *TSInfo) {
16644  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16645 
16646  QualType T = TSInfo->getType();
16647  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16648 
16649  // C++03 [class.friend]p2:
16650  // An elaborated-type-specifier shall be used in a friend declaration
16651  // for a class.*
16652  //
16653  // * The class-key of the elaborated-type-specifier is required.
16654  if (!CodeSynthesisContexts.empty()) {
16655  // Do not complain about the form of friend template types during any kind
16656  // of code synthesis. For template instantiation, we will have complained
16657  // when the template was defined.
16658  } else {
16659  if (!T->isElaboratedTypeSpecifier()) {
16660  // If we evaluated the type to a record type, suggest putting
16661  // a tag in front.
16662  if (const RecordType *RT = T->getAs<RecordType>()) {
16663  RecordDecl *RD = RT->getDecl();
16664 
16665  SmallString<16> InsertionText(" ");
16666  InsertionText += RD->getKindName();
16667 
16668  Diag(TypeRange.getBegin(),
16670  diag::warn_cxx98_compat_unelaborated_friend_type :
16671  diag::ext_unelaborated_friend_type)
16672  << (unsigned) RD->getTagKind()
16673  << T
16675  InsertionText);
16676  } else {
16677  Diag(FriendLoc,
16679  diag::warn_cxx98_compat_nonclass_type_friend :
16680  diag::ext_nonclass_type_friend)
16681  << T
16682  << TypeRange;
16683  }
16684  } else if (T->getAs<EnumType>()) {
16685  Diag(FriendLoc,
16687  diag::warn_cxx98_compat_enum_friend :
16688  diag::ext_enum_friend)
16689  << T
16690  << TypeRange;
16691  }
16692 
16693  // C++11 [class.friend]p3:
16694  // A friend declaration that does not declare a function shall have one
16695  // of the following forms:
16696  // friend elaborated-type-specifier ;
16697  // friend simple-type-specifier ;
16698  // friend typename-specifier ;
16699  if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16700  Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16701  }
16702 
16703  // If the type specifier in a friend declaration designates a (possibly
16704  // cv-qualified) class type, that class is declared as a friend; otherwise,
16705  // the friend declaration is ignored.
16707  TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16708  FriendLoc);
16709 }
16710 
16711 /// Handle a friend tag declaration where the scope specifier was
16712 /// templated.
16714  unsigned TagSpec, SourceLocation TagLoc,
16715  CXXScopeSpec &SS, IdentifierInfo *Name,
16716  SourceLocation NameLoc,
16717  const ParsedAttributesView &Attr,
16718  MultiTemplateParamsArg TempParamLists) {
16720 
16721  bool IsMemberSpecialization = false;
16722  bool Invalid = false;
16723 
16724  if (TemplateParameterList *TemplateParams =
16726  TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16727  IsMemberSpecialization, Invalid)) {
16728  if (TemplateParams->size() > 0) {
16729  // This is a declaration of a class template.
16730  if (Invalid)
16731  return nullptr;
16732 
16733  return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16734  NameLoc, Attr, TemplateParams, AS_public,
16735  /*ModulePrivateLoc=*/SourceLocation(),
16736  FriendLoc, TempParamLists.size() - 1,
16737  TempParamLists.data()).get();
16738  } else {
16739  // The "template<>" header is extraneous.
16740  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16742  IsMemberSpecialization = true;
16743  }
16744  }
16745 
16746  if (Invalid) return nullptr;
16747 
16748  bool isAllExplicitSpecializations = true;
16749  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16750  if (TempParamLists[I]->size()) {
16751  isAllExplicitSpecializations = false;
16752  break;
16753  }
16754  }
16755 
16756  // FIXME: don't ignore attributes.
16757 
16758  // If it's explicit specializations all the way down, just forget
16759  // about the template header and build an appropriate non-templated
16760  // friend. TODO: for source fidelity, remember the headers.
16761  if (isAllExplicitSpecializations) {
16762  if (SS.isEmpty()) {
16763  bool Owned = false;
16764  bool IsDependent = false;
16765  return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16766  Attr, AS_public,
16767  /*ModulePrivateLoc=*/SourceLocation(),
16768  MultiTemplateParamsArg(), Owned, IsDependent,
16769  /*ScopedEnumKWLoc=*/SourceLocation(),
16770  /*ScopedEnumUsesClassTag=*/false,
16771  /*UnderlyingType=*/TypeResult(),
16772  /*IsTypeSpecifier=*/false,
16773  /*IsTemplateParamOrArg=*/false);
16774  }
16775 
16777  ElaboratedTypeKeyword Keyword
16779  QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16780  *Name, NameLoc);
16781  if (T.isNull())
16782  return nullptr;
16783 
16785  if (isa<DependentNameType>(T)) {
16788  TL.setElaboratedKeywordLoc(TagLoc);
16789  TL.setQualifierLoc(QualifierLoc);
16790  TL.setNameLoc(NameLoc);
16791  } else {
16793  TL.setElaboratedKeywordLoc(TagLoc);
16794  TL.setQualifierLoc(QualifierLoc);
16795  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16796  }
16797 
16798  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16799  TSI, FriendLoc, TempParamLists);
16800  Friend->setAccess(AS_public);
16801  CurContext->addDecl(Friend);
16802  return Friend;
16803  }
16804 
16805  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16806 
16807 
16808 
16809  // Handle the case of a templated-scope friend class. e.g.
16810  // template <class T> class A<T>::B;
16811  // FIXME: we don't support these right now.
16812  Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16813  << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16815  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16818  TL.setElaboratedKeywordLoc(TagLoc);
16820  TL.setNameLoc(NameLoc);
16821 
16822  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16823  TSI, FriendLoc, TempParamLists);
16824  Friend->setAccess(AS_public);
16825  Friend->setUnsupportedFriend(true);
16826  CurContext->addDecl(Friend);
16827  return Friend;
16828 }
16829 
16830 /// Handle a friend type declaration. This works in tandem with
16831 /// ActOnTag.
16832 ///
16833 /// Notes on friend class templates:
16834 ///
16835 /// We generally treat friend class declarations as if they were
16836 /// declaring a class. So, for example, the elaborated type specifier
16837 /// in a friend declaration is required to obey the restrictions of a
16838 /// class-head (i.e. no typedefs in the scope chain), template
16839 /// parameters are required to match up with simple template-ids, &c.
16840 /// However, unlike when declaring a template specialization, it's
16841 /// okay to refer to a template specialization without an empty
16842 /// template parameter declaration, e.g.
16843 /// friend class A<T>::B<unsigned>;
16844 /// We permit this as a special case; if there are any template
16845 /// parameters present at all, require proper matching, i.e.
16846 /// template <> template <class T> friend class A<int>::B;
16848  MultiTemplateParamsArg TempParams) {
16849  SourceLocation Loc = DS.getBeginLoc();
16850 
16851  assert(DS.isFriendSpecified());
16853 
16854  // C++ [class.friend]p3:
16855  // A friend declaration that does not declare a function shall have one of
16856  // the following forms:
16857  // friend elaborated-type-specifier ;
16858  // friend simple-type-specifier ;
16859  // friend typename-specifier ;
16860  //
16861  // Any declaration with a type qualifier does not have that form. (It's
16862  // legal to specify a qualified type as a friend, you just can't write the
16863  // keywords.)
16864  if (DS.getTypeQualifiers()) {
16866  Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16868  Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16870  Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16872  Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16874  Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16875  }
16876 
16877  // Try to convert the decl specifier to a type. This works for
16878  // friend templates because ActOnTag never produces a ClassTemplateDecl
16879  // for a TUK_Friend.
16880  Declarator TheDeclarator(DS, DeclaratorContext::Member);
16881  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16882  QualType T = TSI->getType();
16883  if (TheDeclarator.isInvalidType())
16884  return nullptr;
16885 
16887  return nullptr;
16888 
16889  // This is definitely an error in C++98. It's probably meant to
16890  // be forbidden in C++0x, too, but the specification is just
16891  // poorly written.
16892  //
16893  // The problem is with declarations like the following:
16894  // template <T> friend A<T>::foo;
16895  // where deciding whether a class C is a friend or not now hinges
16896  // on whether there exists an instantiation of A that causes
16897  // 'foo' to equal C. There are restrictions on class-heads
16898  // (which we declare (by fiat) elaborated friend declarations to
16899  // be) that makes this tractable.
16900  //
16901  // FIXME: handle "template <> friend class A<T>;", which
16902  // is possibly well-formed? Who even knows?
16903  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16904  Diag(Loc, diag::err_tagless_friend_type_template)
16905  << DS.getSourceRange();
16906  return nullptr;
16907  }
16908 
16909  // C++98 [class.friend]p1: A friend of a class is a function
16910  // or class that is not a member of the class . . .
16911  // This is fixed in DR77, which just barely didn't make the C++03
16912  // deadline. It's also a very silly restriction that seriously
16913  // affects inner classes and which nobody else seems to implement;
16914  // thus we never diagnose it, not even in -pedantic.
16915  //
16916  // But note that we could warn about it: it's always useless to
16917  // friend one of your own members (it's not, however, worthless to
16918  // friend a member of an arbitrary specialization of your template).
16919 
16920  Decl *D;
16921  if (!TempParams.empty())
16923  TempParams,
16924  TSI,
16925  DS.getFriendSpecLoc());
16926  else
16927  D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16928 
16929  if (!D)
16930  return nullptr;
16931 
16932  D->setAccess(AS_public);
16933  CurContext->addDecl(D);
16934 
16935  return D;
16936 }
16937 
16939  MultiTemplateParamsArg TemplateParams) {
16940  const DeclSpec &DS = D.getDeclSpec();
16941 
16942  assert(DS.isFriendSpecified());
16944 
16945  SourceLocation Loc = D.getIdentifierLoc();
16946  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16947 
16948  // C++ [class.friend]p1
16949  // A friend of a class is a function or class....
16950  // Note that this sees through typedefs, which is intended.
16951  // It *doesn't* see through dependent types, which is correct
16952  // according to [temp.arg.type]p3:
16953  // If a declaration acquires a function type through a
16954  // type dependent on a template-parameter and this causes
16955  // a declaration that does not use the syntactic form of a
16956  // function declarator to have a function type, the program
16957  // is ill-formed.
16958  if (!TInfo->getType()->isFunctionType()) {
16959  Diag(Loc, diag::err_unexpected_friend);
16960 
16961  // It might be worthwhile to try to recover by creating an
16962  // appropriate declaration.
16963  return nullptr;
16964  }
16965 
16966  // C++ [namespace.memdef]p3
16967  // - If a friend declaration in a non-local class first declares a
16968  // class or function, the friend class or function is a member
16969  // of the innermost enclosing namespace.
16970  // - The name of the friend is not found by simple name lookup
16971  // until a matching declaration is provided in that namespace
16972  // scope (either before or after the class declaration granting
16973  // friendship).
16974  // - If a friend function is called, its name may be found by the
16975  // name lookup that considers functions from namespaces and
16976  // classes associated with the types of the function arguments.
16977  // - When looking for a prior declaration of a class or a function
16978  // declared as a friend, scopes outside the innermost enclosing
16979  // namespace scope are not considered.
16980 
16981  CXXScopeSpec &SS = D.getCXXScopeSpec();
16983  assert(NameInfo.getName());
16984 
16985  // Check for unexpanded parameter packs.
16989  return nullptr;
16990 
16991  // The context we found the declaration in, or in which we should
16992  // create the declaration.
16993  DeclContext *DC;
16994  Scope *DCScope = S;
16995  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16997 
16998  // There are five cases here.
16999  // - There's no scope specifier and we're in a local class. Only look
17000  // for functions declared in the immediately-enclosing block scope.
17001  // We recover from invalid scope qualifiers as if they just weren't there.
17002  FunctionDecl *FunctionContainingLocalClass = nullptr;
17003  if ((SS.isInvalid() || !SS.isSet()) &&
17004  (FunctionContainingLocalClass =
17005  cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17006  // C++11 [class.friend]p11:
17007  // If a friend declaration appears in a local class and the name
17008  // specified is an unqualified name, a prior declaration is
17009  // looked up without considering scopes that are outside the
17010  // innermost enclosing non-class scope. For a friend function
17011  // declaration, if there is no prior declaration, the program is
17012  // ill-formed.
17013 
17014  // Find the innermost enclosing non-class scope. This is the block
17015  // scope containing the local class definition (or for a nested class,
17016  // the outer local class).
17017  DCScope = S->getFnParent();
17018 
17019  // Look up the function name in the scope.
17021  LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17022 
17023  if (!Previous.empty()) {
17024  // All possible previous declarations must have the same context:
17025  // either they were declared at block scope or they are members of
17026  // one of the enclosing local classes.
17027  DC = Previous.getRepresentativeDecl()->getDeclContext();
17028  } else {
17029  // This is ill-formed, but provide the context that we would have
17030  // declared the function in, if we were permitted to, for error recovery.
17031  DC = FunctionContainingLocalClass;
17032  }
17034 
17035  // C++ [class.friend]p6:
17036  // A function can be defined in a friend declaration of a class if and
17037  // only if the class is a non-local class (9.8), the function name is
17038  // unqualified, and the function has namespace scope.
17039  if (D.isFunctionDefinition()) {
17040  Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17041  }
17042 
17043  // - There's no scope specifier, in which case we just go to the
17044  // appropriate scope and look for a function or function template
17045  // there as appropriate.
17046  } else if (SS.isInvalid() || !SS.isSet()) {
17047  // C++11 [namespace.memdef]p3:
17048  // If the name in a friend declaration is neither qualified nor
17049  // a template-id and the declaration is a function or an
17050  // elaborated-type-specifier, the lookup to determine whether
17051  // the entity has been previously declared shall not consider
17052  // any scopes outside the innermost enclosing namespace.
17053  bool isTemplateId =
17055 
17056  // Find the appropriate context according to the above.
17057  DC = CurContext;
17058 
17059  // Skip class contexts. If someone can cite chapter and verse
17060  // for this behavior, that would be nice --- it's what GCC and
17061  // EDG do, and it seems like a reasonable intent, but the spec
17062  // really only says that checks for unqualified existing
17063  // declarations should stop at the nearest enclosing namespace,
17064  // not that they should only consider the nearest enclosing
17065  // namespace.
17066  while (DC->isRecord())
17067  DC = DC->getParent();
17068 
17069  DeclContext *LookupDC = DC->getNonTransparentContext();
17070  while (true) {
17071  LookupQualifiedName(Previous, LookupDC);
17072 
17073  if (!Previous.empty()) {
17074  DC = LookupDC;
17075  break;
17076  }
17077 
17078  if (isTemplateId) {
17079  if (isa<TranslationUnitDecl>(LookupDC)) break;
17080  } else {
17081  if (LookupDC->isFileContext()) break;
17082  }
17083  LookupDC = LookupDC->getParent();
17084  }
17085 
17086  DCScope = getScopeForDeclContext(S, DC);
17087 
17088  // - There's a non-dependent scope specifier, in which case we
17089  // compute it and do a previous lookup there for a function
17090  // or function template.
17091  } else if (!SS.getScopeRep()->isDependent()) {
17092  DC = computeDeclContext(SS);
17093  if (!DC) return nullptr;
17094 
17095  if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17096 
17098 
17099  // C++ [class.friend]p1: A friend of a class is a function or
17100  // class that is not a member of the class . . .
17101  if (DC->Equals(CurContext))
17102  Diag(DS.getFriendSpecLoc(),
17104  diag::warn_cxx98_compat_friend_is_member :
17105  diag::err_friend_is_member);
17106 
17107  if (D.isFunctionDefinition()) {
17108  // C++ [class.friend]p6:
17109  // A function can be defined in a friend declaration of a class if and
17110  // only if the class is a non-local class (9.8), the function name is
17111  // unqualified, and the function has namespace scope.
17112  //
17113  // FIXME: We should only do this if the scope specifier names the
17114  // innermost enclosing namespace; otherwise the fixit changes the
17115  // meaning of the code.
17117  = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17118 
17119  DB << SS.getScopeRep();
17120  if (DC->isFileContext())
17121  DB << FixItHint::CreateRemoval(SS.getRange());
17122  SS.clear();
17123  }
17124 
17125  // - There's a scope specifier that does not match any template
17126  // parameter lists, in which case we use some arbitrary context,
17127  // create a method or method template, and wait for instantiation.
17128  // - There's a scope specifier that does match some template
17129  // parameter lists, which we don't handle right now.
17130  } else {
17131  if (D.isFunctionDefinition()) {
17132  // C++ [class.friend]p6:
17133  // A function can be defined in a friend declaration of a class if and
17134  // only if the class is a non-local class (9.8), the function name is
17135  // unqualified, and the function has namespace scope.
17136  Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17137  << SS.getScopeRep();
17138  }
17139 
17140  DC = CurContext;
17141  assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17142  }
17143 
17144  if (!DC->isRecord()) {
17145  int DiagArg = -1;
17146  switch (D.getName().getKind()) {
17149  DiagArg = 0;
17150  break;
17152  DiagArg = 1;
17153  break;
17155  DiagArg = 2;
17156  break;
17158  DiagArg = 3;
17159  break;
17165  break;
17166  }
17167  // This implies that it has to be an operator or function.
17168  if (DiagArg >= 0) {
17169  Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17170  return nullptr;
17171  }
17172  }
17173 
17174  // FIXME: This is an egregious hack to cope with cases where the scope stack
17175  // does not contain the declaration context, i.e., in an out-of-line
17176  // definition of a class.
17177  Scope FakeDCScope(S, Scope::DeclScope, Diags);
17178  if (!DCScope) {
17179  FakeDCScope.setEntity(DC);
17180  DCScope = &FakeDCScope;
17181  }
17182 
17183  bool AddToScope = true;
17184  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17185  TemplateParams, AddToScope);
17186  if (!ND) return nullptr;
17187 
17188  assert(ND->getLexicalDeclContext() == CurContext);
17189 
17190  // If we performed typo correction, we might have added a scope specifier
17191  // and changed the decl context.
17192  DC = ND->getDeclContext();
17193 
17194  // Add the function declaration to the appropriate lookup tables,
17195  // adjusting the redeclarations list as necessary. We don't
17196  // want to do this yet if the friending class is dependent.
17197  //
17198  // Also update the scope-based lookup if the target context's
17199  // lookup context is in lexical scope.
17200  if (!CurContext->isDependentContext()) {
17201  DC = DC->getRedeclContext();
17202  DC->makeDeclVisibleInContext(ND);
17203  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17204  PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17205  }
17206 
17208  D.getIdentifierLoc(), ND,
17209  DS.getFriendSpecLoc());
17210  FrD->setAccess(AS_public);
17211  CurContext->addDecl(FrD);
17212 
17213  if (ND->isInvalidDecl()) {
17214  FrD->setInvalidDecl();
17215  } else {
17216  if (DC->isRecord()) CheckFriendAccess(ND);
17217 
17218  FunctionDecl *FD;
17219  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17220  FD = FTD->getTemplatedDecl();
17221  else
17222  FD = cast<FunctionDecl>(ND);
17223 
17224  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17225  // default argument expression, that declaration shall be a definition
17226  // and shall be the only declaration of the function or function
17227  // template in the translation unit.
17229  // We can't look at FD->getPreviousDecl() because it may not have been set
17230  // if we're in a dependent context. If the function is known to be a
17231  // redeclaration, we will have narrowed Previous down to the right decl.
17232  if (D.isRedeclaration()) {
17233  Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17234  Diag(Previous.getRepresentativeDecl()->getLocation(),
17235  diag::note_previous_declaration);
17236  } else if (!D.isFunctionDefinition())
17237  Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17238  }
17239 
17240  // Mark templated-scope function declarations as unsupported.
17241  if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17242  Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17243  << SS.getScopeRep() << SS.getRange()
17244  << cast<CXXRecordDecl>(CurContext);
17245  FrD->setUnsupportedFriend(true);
17246  }
17247  }
17248 
17250 
17251  return ND;
17252 }
17253 
17255  AdjustDeclIfTemplate(Dcl);
17256 
17257  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17258  if (!Fn) {
17259  Diag(DelLoc, diag::err_deleted_non_function);
17260  return;
17261  }
17262 
17263  // Deleted function does not have a body.
17264  Fn->setWillHaveBody(false);
17265 
17266  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17267  // Don't consider the implicit declaration we generate for explicit
17268  // specializations. FIXME: Do not generate these implicit declarations.
17269  if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17270  Prev->getPreviousDecl()) &&
17271  !Prev->isDefined()) {
17272  Diag(DelLoc, diag::err_deleted_decl_not_first);
17273  Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17274  Prev->isImplicit() ? diag::note_previous_implicit_declaration
17275  : diag::note_previous_declaration);
17276  // We can't recover from this; the declaration might have already
17277  // been used.
17278  Fn->setInvalidDecl();
17279  return;
17280  }
17281 
17282  // To maintain the invariant that functions are only deleted on their first
17283  // declaration, mark the implicitly-instantiated declaration of the
17284  // explicitly-specialized function as deleted instead of marking the
17285  // instantiated redeclaration.
17286  Fn = Fn->getCanonicalDecl();
17287  }
17288 
17289  // dllimport/dllexport cannot be deleted.
17290  if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17291  Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17292  Fn->setInvalidDecl();
17293  }
17294 
17295  // C++11 [basic.start.main]p3:
17296  // A program that defines main as deleted [...] is ill-formed.
17297  if (Fn->isMain())
17298  Diag(DelLoc, diag::err_deleted_main);
17299 
17300  // C++11 [dcl.fct.def.delete]p4:
17301  // A deleted function is implicitly inline.
17302  Fn->setImplicitlyInline();
17303  Fn->setDeletedAsWritten();
17304 }
17305 
17307  if (!Dcl || Dcl->isInvalidDecl())
17308  return;
17309 
17310  auto *FD = dyn_cast<FunctionDecl>(Dcl);
17311  if (!FD) {
17312  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17313  if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17314  Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17315  return;
17316  }
17317  }
17318 
17319  Diag(DefaultLoc, diag::err_default_special_members)
17320  << getLangOpts().CPlusPlus20;
17321  return;
17322  }
17323 
17324  // Reject if this can't possibly be a defaultable function.
17326  if (!DefKind &&
17327  // A dependent function that doesn't locally look defaultable can
17328  // still instantiate to a defaultable function if it's a constructor
17329  // or assignment operator.
17330  (!FD->isDependentContext() ||
17331  (!isa<CXXConstructorDecl>(FD) &&
17332  FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17333  Diag(DefaultLoc, diag::err_default_special_members)
17334  << getLangOpts().CPlusPlus20;
17335  return;
17336  }
17337 
17338  // Issue compatibility warning. We already warned if the operator is
17339  // 'operator<=>' when parsing the '<=>' token.
17340  if (DefKind.isComparison() &&
17342  Diag(DefaultLoc, getLangOpts().CPlusPlus20
17343  ? diag::warn_cxx17_compat_defaulted_comparison
17344  : diag::ext_defaulted_comparison);
17345  }
17346 
17347  FD->setDefaulted();
17348  FD->setExplicitlyDefaulted();
17349 
17350  // Defer checking functions that are defaulted in a dependent context.
17351  if (FD->isDependentContext())
17352  return;
17353 
17354  // Unset that we will have a body for this function. We might not,
17355  // if it turns out to be trivial, and we don't need this marking now
17356  // that we've marked it as defaulted.
17357  FD->setWillHaveBody(false);
17358 
17359  if (DefKind.isComparison()) {
17360  // If this comparison's defaulting occurs within the definition of its
17361  // lexical class context, we have to do the checking when complete.
17362  if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17363  if (!RD->isCompleteDefinition())
17364  return;
17365  }
17366 
17367  // If this member fn was defaulted on its first declaration, we will have
17368  // already performed the checking in CheckCompletedCXXClass. Such a
17369  // declaration doesn't trigger an implicit definition.
17370  if (isa<CXXMethodDecl>(FD)) {
17371  const FunctionDecl *Primary = FD;
17372  if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17373  // Ask the template instantiation pattern that actually had the
17374  // '= default' on it.
17375  Primary = Pattern;
17376  if (Primary->getCanonicalDecl()->isDefaulted())
17377  return;
17378  }
17379 
17380  if (DefKind.isComparison()) {
17381  if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17382  FD->setInvalidDecl();
17383  else
17384  DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17385  } else {
17386  auto *MD = cast<CXXMethodDecl>(FD);
17387 
17389  MD->setInvalidDecl();
17390  else
17391  DefineDefaultedFunction(*this, MD, DefaultLoc);
17392  }
17393 }
17394 
17395 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17396  for (Stmt *SubStmt : S->children()) {
17397  if (!SubStmt)
17398  continue;
17399  if (isa<ReturnStmt>(SubStmt))
17400  Self.Diag(SubStmt->getBeginLoc(),
17401  diag::err_return_in_constructor_handler);
17402  if (!isa<Expr>(SubStmt))
17403  SearchForReturnInStmt(Self, SubStmt);
17404  }
17405 }
17406 
17408  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17409  CXXCatchStmt *Handler = TryBlock->getHandler(I);
17410  SearchForReturnInStmt(*this, Handler);
17411  }
17412 }
17413 
17415  const CXXMethodDecl *Old) {
17416  const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17417  const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17418 
17419  if (OldFT->hasExtParameterInfos()) {
17420  for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17421  // A parameter of the overriding method should be annotated with noescape
17422  // if the corresponding parameter of the overridden method is annotated.
17423  if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17424  !NewFT->getExtParameterInfo(I).isNoEscape()) {
17425  Diag(New->getParamDecl(I)->getLocation(),
17426  diag::warn_overriding_method_missing_noescape);
17427  Diag(Old->getParamDecl(I)->getLocation(),
17428  diag::note_overridden_marked_noescape);
17429  }
17430  }
17431 
17432  // Virtual overrides must have the same code_seg.
17433  const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17434  const auto *NewCSA = New->getAttr<CodeSegAttr>();
17435  if ((NewCSA || OldCSA) &&
17436  (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17437  Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17438  Diag(Old->getLocation(), diag::note_previous_declaration);
17439  return true;
17440  }
17441 
17442  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17443 
17444  // If the calling conventions match, everything is fine
17445  if (NewCC == OldCC)
17446  return false;
17447 
17448  // If the calling conventions mismatch because the new function is static,
17449  // suppress the calling convention mismatch error; the error about static
17450  // function override (err_static_overrides_virtual from
17451  // Sema::CheckFunctionDeclaration) is more clear.
17452  if (New->getStorageClass() == SC_Static)
17453  return false;
17454 
17455  Diag(New->getLocation(),
17456  diag::err_conflicting_overriding_cc_attributes)
17457  << New->getDeclName() << New->getType() << Old->getType();
17458  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17459  return true;
17460 }
17461 
17463  const CXXMethodDecl *Old) {
17464  QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17465  QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17466 
17467  if (Context.hasSameType(NewTy, OldTy) ||
17468  NewTy->isDependentType() || OldTy->isDependentType())
17469  return false;
17470 
17471  // Check if the return types are covariant
17472  QualType NewClassTy, OldClassTy;
17473 
17474  /// Both types must be pointers or references to classes.
17475  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17476  if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17477  NewClassTy = NewPT->getPointeeType();
17478  OldClassTy = OldPT->getPointeeType();
17479  }
17480  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17481  if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17482  if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17483  NewClassTy = NewRT->getPointeeType();
17484  OldClassTy = OldRT->getPointeeType();
17485  }
17486  }
17487  }
17488 
17489  // The return types aren't either both pointers or references to a class type.
17490  if (NewClassTy.isNull()) {
17491  Diag(New->getLocation(),
17492  diag::err_different_return_type_for_overriding_virtual_function)
17493  << New->getDeclName() << NewTy << OldTy
17494  << New->getReturnTypeSourceRange();
17495  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17496  << Old->getReturnTypeSourceRange();
17497 
17498  return true;
17499  }
17500 
17501  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17502  // C++14 [class.virtual]p8:
17503  // If the class type in the covariant return type of D::f differs from
17504  // that of B::f, the class type in the return type of D::f shall be
17505  // complete at the point of declaration of D::f or shall be the class
17506  // type D.
17507  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17508  if (!RT->isBeingDefined() &&
17509  RequireCompleteType(New->getLocation(), NewClassTy,
17510  diag::err_covariant_return_incomplete,
17511  New->getDeclName()))
17512  return true;
17513  }
17514 
17515  // Check if the new class derives from the old class.
17516  if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17517  Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17518  << New->getDeclName() << NewTy << OldTy
17519  << New->getReturnTypeSourceRange();
17520  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17521  << Old->getReturnTypeSourceRange();
17522  return true;
17523  }
17524 
17525  // Check if we the conversion from derived to base is valid.
17527  NewClassTy, OldClassTy,
17528  diag::err_covariant_return_inaccessible_base,
17529  diag::err_covariant_return_ambiguous_derived_to_base_conv,
17530  New->getLocation(), New->getReturnTypeSourceRange(),
17531  New->getDeclName(), nullptr)) {
17532  // FIXME: this note won't trigger for delayed access control
17533  // diagnostics, and it's impossible to get an undelayed error
17534  // here from access control during the original parse because
17535  // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17536  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17537  << Old->getReturnTypeSourceRange();
17538  return true;
17539  }
17540  }
17541 
17542  // The qualifiers of the return types must be the same.
17543  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17544  Diag(New->getLocation(),
17545  diag::err_covariant_return_type_different_qualifications)
17546  << New->getDeclName() << NewTy << OldTy
17547  << New->getReturnTypeSourceRange();
17548  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17549  << Old->getReturnTypeSourceRange();
17550  return true;
17551  }
17552 
17553 
17554  // The new class type must have the same or less qualifiers as the old type.
17555  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17556  Diag(New->getLocation(),
17557  diag::err_covariant_return_type_class_type_more_qualified)
17558  << New->getDeclName() << NewTy << OldTy
17559  << New->getReturnTypeSourceRange();
17560  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17561  << Old->getReturnTypeSourceRange();
17562  return true;
17563  }
17564 
17565  return false;
17566 }
17567 
17568 /// Mark the given method pure.
17569 ///
17570 /// \param Method the method to be marked pure.
17571 ///
17572 /// \param InitRange the source range that covers the "0" initializer.
17574  SourceLocation EndLoc = InitRange.getEnd();
17575  if (EndLoc.isValid())
17576  Method->setRangeEnd(EndLoc);
17577 
17578  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17579  Method->setPure();
17580  return false;
17581  }
17582 
17583  if (!Method->isInvalidDecl())
17584  Diag(Method->getLocation(), diag::err_non_virtual_pure)
17585  << Method->getDeclName() << InitRange;
17586  return true;
17587 }
17588 
17590  if (D->getFriendObjectKind())
17591  Diag(D->getLocation(), diag::err_pure_friend);
17592  else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17593  CheckPureMethod(M, ZeroLoc);
17594  else
17595  Diag(D->getLocation(), diag::err_illegal_initializer);
17596 }
17597 
17598 /// Determine whether the given declaration is a global variable or
17599 /// static data member.
17600 static bool isNonlocalVariable(const Decl *D) {
17601  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17602  return Var->hasGlobalStorage();
17603 
17604  return false;
17605 }
17606 
17607 /// Invoked when we are about to parse an initializer for the declaration
17608 /// 'Dcl'.
17609 ///
17610 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17611 /// static data member of class X, names should be looked up in the scope of
17612 /// class X. If the declaration had a scope specifier, a scope will have
17613 /// been created and passed in for this purpose. Otherwise, S will be null.
17615  // If there is no declaration, there was an error parsing it.
17616  if (!D || D->isInvalidDecl())
17617  return;
17618 
17619  // We will always have a nested name specifier here, but this declaration
17620  // might not be out of line if the specifier names the current namespace:
17621  // extern int n;
17622  // int ::n = 0;
17623  if (S && D->isOutOfLine())
17625 
17626  // If we are parsing the initializer for a static data member, push a
17627  // new expression evaluation context that is associated with this static
17628  // data member.
17629  if (isNonlocalVariable(D))
17632 }
17633 
17634 /// Invoked after we are finished parsing an initializer for the declaration D.
17636  // If there is no declaration, there was an error parsing it.
17637  if (!D || D->isInvalidDecl())
17638  return;
17639 
17640  if (isNonlocalVariable(D))
17642 
17643  if (S && D->isOutOfLine())
17645 }
17646 
17647 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17648 /// C++ if/switch/while/for statement.
17649 /// e.g: "if (int x = f()) {...}"
17651  // C++ 6.4p2:
17652  // The declarator shall not specify a function or an array.
17653  // The type-specifier-seq shall not contain typedef and shall not declare a
17654  // new class or enumeration.
17656  "Parser allowed 'typedef' as storage class of condition decl.");
17657 
17658  Decl *Dcl = ActOnDeclarator(S, D);
17659  if (!Dcl)
17660  return true;
17661 
17662  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17663  Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17664  << D.getSourceRange();
17665  return true;
17666  }
17667 
17668  return Dcl;
17669 }
17670 
17672  if (!ExternalSource)
17673  return;
17674 
17676  ExternalSource->ReadUsedVTables(VTables);
17677  SmallVector<VTableUse, 4> NewUses;
17678  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17679  llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17680  = VTablesUsed.find(VTables[I].Record);
17681  // Even if a definition wasn't required before, it may be required now.
17682  if (Pos != VTablesUsed.end()) {
17683  if (!Pos->second && VTables[I].DefinitionRequired)
17684  Pos->second = true;
17685  continue;
17686  }
17687 
17688  VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17689  NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17690  }
17691 
17692  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17693 }
17694 
17696  bool DefinitionRequired) {
17697  // Ignore any vtable uses in unevaluated operands or for classes that do
17698  // not have a vtable.
17699  if (!Class->isDynamicClass() || Class->isDependentContext() ||
17701  return;
17702  // Do not mark as used if compiling for the device outside of the target
17703  // region.
17704  if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17707  if (!DefinitionRequired)
17708  MarkVirtualMembersReferenced(Loc, Class);
17709  return;
17710  }
17711 
17712  // Try to insert this class into the map.
17714  Class = Class->getCanonicalDecl();
17715  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17716  Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17717  if (!Pos.second) {
17718  // If we already had an entry, check to see if we are promoting this vtable
17719  // to require a definition. If so, we need to reappend to the VTableUses
17720  // list, since we may have already processed the first entry.
17721  if (DefinitionRequired && !Pos.first->second) {
17722  Pos.first->second = true;
17723  } else {
17724  // Otherwise, we can early exit.
17725  return;
17726  }
17727  } else {
17728  // The Microsoft ABI requires that we perform the destructor body
17729  // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17730  // the deleting destructor is emitted with the vtable, not with the
17731  // destructor definition as in the Itanium ABI.
17733  CXXDestructorDecl *DD = Class->getDestructor();
17734  if (DD && DD->isVirtual() && !DD->isDeleted()) {
17735  if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17736  // If this is an out-of-line declaration, marking it referenced will
17737  // not do anything. Manually call CheckDestructor to look up operator
17738  // delete().
17739  ContextRAII SavedContext(*this, DD);
17740  CheckDestructor(DD);
17741  } else {
17742  MarkFunctionReferenced(Loc, Class->getDestructor());
17743  }
17744  }
17745  }
17746  }
17747 
17748  // Local classes need to have their virtual members marked
17749  // immediately. For all other classes, we mark their virtual members
17750  // at the end of the translation unit.
17751  if (Class->isLocalClass())
17752  MarkVirtualMembersReferenced(Loc, Class);
17753  else
17754  VTableUses.push_back(std::make_pair(Class, Loc));
17755 }
17756 
17759  if (VTableUses.empty())
17760  return false;
17761 
17762  // Note: The VTableUses vector could grow as a result of marking
17763  // the members of a class as "used", so we check the size each
17764  // time through the loop and prefer indices (which are stable) to
17765  // iterators (which are not).
17766  bool DefinedAnything = false;
17767  for (unsigned I = 0; I != VTableUses.size(); ++I) {
17768  CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17769  if (!Class)
17770  continue;
17771  TemplateSpecializationKind ClassTSK =
17772  Class->getTemplateSpecializationKind();
17773 
17774  SourceLocation Loc = VTableUses[I].second;
17775 
17776  bool DefineVTable = true;
17777 
17778  // If this class has a key function, but that key function is
17779  // defined in another translation unit, we don't need to emit the
17780  // vtable even though we're using it.
17781  const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17782  if (KeyFunction && !KeyFunction->hasBody()) {
17783  // The key function is in another translation unit.
17784  DefineVTable = false;
17786  KeyFunction->getTemplateSpecializationKind();
17787  assert(TSK != TSK_ExplicitInstantiationDefinition &&
17788  TSK != TSK_ImplicitInstantiation &&
17789  "Instantiations don't have key functions");
17790  (void)TSK;
17791  } else if (!KeyFunction) {
17792  // If we have a class with no key function that is the subject
17793  // of an explicit instantiation declaration, suppress the
17794  // vtable; it will live with the explicit instantiation
17795  // definition.
17796  bool IsExplicitInstantiationDeclaration =
17798  for (auto R : Class->redecls()) {
17800  = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17802  IsExplicitInstantiationDeclaration = true;
17803  else if (TSK == TSK_ExplicitInstantiationDefinition) {
17804  IsExplicitInstantiationDeclaration = false;
17805  break;
17806  }
17807  }
17808 
17809  if (IsExplicitInstantiationDeclaration)
17810  DefineVTable = false;
17811  }
17812 
17813  // The exception specifications for all virtual members may be needed even
17814  // if we are not providing an authoritative form of the vtable in this TU.
17815  // We may choose to emit it available_externally anyway.
17816  if (!DefineVTable) {
17818  continue;
17819  }
17820 
17821  // Mark all of the virtual members of this class as referenced, so
17822  // that we can build a vtable. Then, tell the AST consumer that a
17823  // vtable for this class is required.
17824  DefinedAnything = true;
17825  MarkVirtualMembersReferenced(Loc, Class);
17826  CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17827  if (VTablesUsed[Canonical])
17828  Consumer.HandleVTable(Class);
17829 
17830  // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17831  // no key function or the key function is inlined. Don't warn in C++ ABIs
17832  // that lack key functions, since the user won't be able to make one.
17834  Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17836  const FunctionDecl *KeyFunctionDef = nullptr;
17837  if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17838  KeyFunctionDef->isInlined()))
17839  Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17840  }
17841  }
17842  VTableUses.clear();
17843 
17844  return DefinedAnything;
17845 }
17846 
17848  const CXXRecordDecl *RD) {
17849  for (const auto *I : RD->methods())
17850  if (I->isVirtual() && !I->isPure())
17851  ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17852 }
17853 
17855  const CXXRecordDecl *RD,
17856  bool ConstexprOnly) {
17857  // Mark all functions which will appear in RD's vtable as used.
17858  CXXFinalOverriderMap FinalOverriders;
17859  RD->getFinalOverriders(FinalOverriders);
17860  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17861  E = FinalOverriders.end();
17862  I != E; ++I) {
17863  for (OverridingMethods::const_iterator OI = I->second.begin(),
17864  OE = I->second.end();
17865  OI != OE; ++OI) {
17866  assert(OI->second.size() > 0 && "no final overrider");
17867  CXXMethodDecl *Overrider = OI->second.front().Method;
17868 
17869  // C++ [basic.def.odr]p2:
17870  // [...] A virtual member function is used if it is not pure. [...]
17871  if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17872  MarkFunctionReferenced(Loc, Overrider);
17873  }
17874  }
17875 
17876  // Only classes that have virtual bases need a VTT.
17877  if (RD->getNumVBases() == 0)
17878  return;
17879 
17880  for (const auto &I : RD->bases()) {
17881  const auto *Base =
17882  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17883  if (Base->getNumVBases() == 0)
17884  continue;
17886  }
17887 }
17888 
17889 /// SetIvarInitializers - This routine builds initialization ASTs for the
17890 /// Objective-C implementation whose ivars need be initialized.
17892  if (!getLangOpts().CPlusPlus)
17893  return;
17894  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17897  if (ivars.empty())
17898  return;
17900  for (unsigned i = 0; i < ivars.size(); i++) {
17901  FieldDecl *Field = ivars[i];
17902  if (Field->isInvalidDecl())
17903  continue;
17904 
17907  InitializationKind InitKind =
17908  InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17909 
17910  InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17911  ExprResult MemberInit =
17912  InitSeq.Perform(*this, InitEntity, InitKind, None);
17913  MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17914  // Note, MemberInit could actually come back empty if no initialization
17915  // is required (e.g., because it would call a trivial default constructor)
17916  if (!MemberInit.get() || MemberInit.isInvalid())
17917  continue;
17918 
17919  Member =
17921  SourceLocation(),
17922  MemberInit.getAs<Expr>(),
17923  SourceLocation());
17924  AllToInit.push_back(Member);
17925 
17926  // Be sure that the destructor is accessible and is marked as referenced.
17927  if (const RecordType *RecordTy =
17928  Context.getBaseElementType(Field->getType())
17929  ->getAs<RecordType>()) {
17930  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17931  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17932  MarkFunctionReferenced(Field->getLocation(), Destructor);
17933  CheckDestructorAccess(Field->getLocation(), Destructor,
17934  PDiag(diag::err_access_dtor_ivar)
17935  << Context.getBaseElementType(Field->getType()));
17936  }
17937  }
17938  }
17939  ObjCImplementation->setIvarInitializers(Context,
17940  AllToInit.data(), AllToInit.size());
17941  }
17942 }
17943 
17944 static
17949  Sema &S) {
17950  if (Ctor->isInvalidDecl())
17951  return;
17952 
17954 
17955  // Target may not be determinable yet, for instance if this is a dependent
17956  // call in an uninstantiated template.
17957  if (Target) {
17958  const FunctionDecl *FNTarget = nullptr;
17959  (void)Target->hasBody(FNTarget);
17960  Target = const_cast<CXXConstructorDecl*>(
17961  cast_or_null<CXXConstructorDecl>(FNTarget));
17962  }
17963 
17964  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17965  // Avoid dereferencing a null pointer here.
17966  *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17967 
17968  if (!Current.insert(Canonical).second)
17969  return;
17970 
17971  // We know that beyond here, we aren't chaining into a cycle.
17972  if (!Target || !Target->isDelegatingConstructor() ||
17973  Target->isInvalidDecl() || Valid.count(TCanonical)) {
17974  Valid.insert(Current.begin(), Current.end());
17975  Current.clear();
17976  // We've hit a cycle.
17977  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17978  Current.count(TCanonical)) {
17979  // If we haven't diagnosed this cycle yet, do so now.
17980  if (!Invalid.count(TCanonical)) {
17981  S.Diag((*Ctor->init_begin())->getSourceLocation(),
17982  diag::warn_delegating_ctor_cycle)
17983  << Ctor;
17984 
17985  // Don't add a note for a function delegating directly to itself.
17986  if (TCanonical != Canonical)
17987  S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17988 
17990  while (C->getCanonicalDecl() != Canonical) {
17991  const FunctionDecl *FNTarget = nullptr;
17992  (void)C->getTargetConstructor()->hasBody(FNTarget);
17993  assert(FNTarget && "Ctor cycle through bodiless function");
17994 
17995  C = const_cast<CXXConstructorDecl*>(
17996  cast<CXXConstructorDecl>(FNTarget));
17997  S.Diag(C->getLocation(), diag::note_which_delegates_to);
17998  }
17999  }
18000 
18001  Invalid.insert(Current.begin(), Current.end());
18002  Current.clear();
18003  } else {
18004  DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18005  }
18006 }
18007 
18008 
18010  llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18011 
18012  for (DelegatingCtorDeclsType::iterator
18013  I = DelegatingCtorDecls.begin(ExternalSource),
18014  E = DelegatingCtorDecls.end();
18015  I != E; ++I)
18016  DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18017 
18018  for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18019  (*CI)->setInvalidDecl();
18020 }
18021 
18022 namespace {
18023  /// AST visitor that finds references to the 'this' expression.
18024  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18025  Sema &S;
18026 
18027  public:
18028  explicit FindCXXThisExpr(Sema &S) : S(S) { }
18029 
18030  bool VisitCXXThisExpr(CXXThisExpr *E) {
18031  S.Diag(E->getLocation(), diag::err_this_static_member_func)
18032  << E->isImplicit();
18033  return false;
18034  }
18035  };
18036 }
18037 
18039  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18040  if (!TSInfo)
18041  return false;
18042 
18043  TypeLoc TL = TSInfo->getTypeLoc();
18045  if (!ProtoTL)
18046  return false;
18047 
18048  // C++11 [expr.prim.general]p3:
18049  // [The expression this] shall not appear before the optional
18050  // cv-qualifier-seq and it shall not appear within the declaration of a
18051  // static member function (although its type and value category are defined
18052  // within a static member function as they are within a non-static member
18053  // function). [ Note: this is because declaration matching does not occur
18054  // until the complete declarator is known. - end note ]
18055  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18056  FindCXXThisExpr Finder(*this);
18057 
18058  // If the return type came after the cv-qualifier-seq, check it now.
18059  if (Proto->hasTrailingReturn() &&
18060  !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18061  return true;
18062 
18063  // Check the exception specification.
18065  return true;
18066 
18067  // Check the trailing requires clause
18068  if (Expr *E = Method->getTrailingRequiresClause())
18069  if (!Finder.TraverseStmt(E))
18070  return true;
18071 
18073 }
18074 
18076  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18077  if (!TSInfo)
18078  return false;
18079 
18080  TypeLoc TL = TSInfo->getTypeLoc();
18082  if (!ProtoTL)
18083  return false;
18084 
18085  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18086  FindCXXThisExpr Finder(*this);
18087 
18088  switch (Proto->getExceptionSpecType()) {
18089  case EST_Unparsed:
18090  case EST_Uninstantiated:
18091  case EST_Unevaluated:
18092  case EST_BasicNoexcept:
18093  case EST_NoThrow:
18094  case EST_DynamicNone:
18095  case EST_MSAny:
18096  case EST_None:
18097  break;
18098 
18099  case EST_DependentNoexcept:
18100  case EST_NoexceptFalse:
18101  case EST_NoexceptTrue:
18102  if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18103  return true;
18104  LLVM_FALLTHROUGH;
18105 
18106  case EST_Dynamic:
18107  for (const auto &E : Proto->exceptions()) {
18108  if (!Finder.TraverseType(E))
18109  return true;
18110  }
18111  break;
18112  }
18113 
18114  return false;
18115 }
18116 
18118  FindCXXThisExpr Finder(*this);
18119 
18120  // Check attributes.
18121  for (const auto *A : Method->attrs()) {
18122  // FIXME: This should be emitted by tblgen.
18123  Expr *Arg = nullptr;
18124  ArrayRef<Expr *> Args;
18125  if (const auto *G = dyn_cast<GuardedByAttr>(A))
18126  Arg = G->getArg();
18127  else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18128  Arg = G->getArg();
18129  else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18130  Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18131  else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18132  Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18133  else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18134  Arg = ETLF->getSuccessValue();
18135  Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18136  } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18137  Arg = STLF->getSuccessValue();
18138  Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18139  } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18140  Arg = LR->getArg();
18141  else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18142  Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18143  else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18144  Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18145  else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18146  Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18147  else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18148  Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18149  else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18150  Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18151 
18152  if (Arg && !Finder.TraverseStmt(Arg))
18153  return true;
18154 
18155  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18156  if (!Finder.TraverseStmt(Args[I]))
18157  return true;
18158  }
18159  }
18160 
18161  return false;
18162 }
18163 
18165  bool IsTopLevel, ExceptionSpecificationType EST,
18166  ArrayRef<ParsedType> DynamicExceptions,
18167  ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18168  SmallVectorImpl<QualType> &Exceptions,
18170  Exceptions.clear();
18171  ESI.Type = EST;
18172  if (EST == EST_Dynamic) {
18173  Exceptions.reserve(DynamicExceptions.size());
18174  for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18175  // FIXME: Preserve type source info.
18176  QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18177 
18178  if (IsTopLevel) {
18180  collectUnexpandedParameterPacks(ET, Unexpanded);
18181  if (!Unexpanded.empty()) {
18183  DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18184  Unexpanded);
18185  continue;
18186  }
18187  }
18188 
18189  // Check that the type is valid for an exception spec, and
18190  // drop it if not.
18191  if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18192  Exceptions.push_back(ET);
18193  }
18194  ESI.Exceptions = Exceptions;
18195  return;
18196  }
18197 
18198  if (isComputedNoexcept(EST)) {
18199  assert((NoexceptExpr->isTypeDependent() ||
18200  NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18201  Context.BoolTy) &&
18202  "Parser should have made sure that the expression is boolean");
18203  if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18204  ESI.Type = EST_BasicNoexcept;
18205  return;
18206  }
18207 
18208  ESI.NoexceptExpr = NoexceptExpr;
18209  return;
18210  }
18211 }
18212 
18215  SourceRange SpecificationRange,
18216  ArrayRef<ParsedType> DynamicExceptions,
18217  ArrayRef<SourceRange> DynamicExceptionRanges,
18218  Expr *NoexceptExpr) {
18219  if (!MethodD)
18220  return;
18221 
18222  // Dig out the method we're referring to.
18223  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18224  MethodD = FunTmpl->getTemplatedDecl();
18225 
18226  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18227  if (!Method)
18228  return;
18229 
18230  // Check the exception specification.
18231  llvm::SmallVector<QualType, 4> Exceptions;
18233  checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18234  DynamicExceptionRanges, NoexceptExpr, Exceptions,
18235  ESI);
18236 
18237  // Update the exception specification on the function type.
18238  Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18239 
18240  if (Method->isStatic())
18242 
18243  if (Method->isVirtual()) {
18244  // Check overrides, which we previously had to delay.
18245  for (const CXXMethodDecl *O : Method->overridden_methods())
18247  }
18248 }
18249 
18250 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18251 ///
18253  SourceLocation DeclStart, Declarator &D,
18254  Expr *BitWidth,
18255  InClassInitStyle InitStyle,
18256  AccessSpecifier AS,
18257  const ParsedAttr &MSPropertyAttr) {
18258  IdentifierInfo *II = D.getIdentifier();
18259  if (!II) {
18260  Diag(DeclStart, diag::err_anonymous_property);
18261  return nullptr;
18262  }
18263  SourceLocation Loc = D.getIdentifierLoc();
18264 
18265  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18266  QualType T = TInfo->getType();
18267  if (getLangOpts().CPlusPlus) {
18269 
18272  D.setInvalidType();
18273  T = Context.IntTy;
18274  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18275  }
18276  }
18277 
18279 
18280  if (D.getDeclSpec().isInlineSpecified())
18281  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18282  << getLangOpts().CPlusPlus17;
18285  diag::err_invalid_thread)
18286  << DeclSpec::getSpecifierName(TSCS);
18287 
18288  // Check to see if this name was declared as a member previously
18289  NamedDecl *PrevDecl = nullptr;
18290  LookupResult Previous(*this, II, Loc, LookupMemberName,
18292  LookupName(Previous, S);
18293  switch (Previous.getResultKind()) {
18294  case LookupResult::Found:
18296  PrevDecl = Previous.getAsSingle<NamedDecl>();
18297  break;
18298 
18300  PrevDecl = Previous.getRepresentativeDecl();
18301  break;
18302 
18306  break;
18307  }
18308 
18309  if (PrevDecl && PrevDecl->isTemplateParameter()) {
18310  // Maybe we will complain about the shadowed template parameter.
18312  // Just pretend that we didn't see the previous declaration.
18313  PrevDecl = nullptr;
18314  }
18315 
18316  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18317  PrevDecl = nullptr;
18318 
18319  SourceLocation TSSL = D.getBeginLoc();
18320  MSPropertyDecl *NewPD =
18321  MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18322  MSPropertyAttr.getPropertyDataGetter(),
18323  MSPropertyAttr.getPropertyDataSetter());
18324  ProcessDeclAttributes(TUScope, NewPD, D);
18325  NewPD->setAccess(AS);
18326 
18327  if (NewPD->isInvalidDecl())
18328  Record->setInvalidDecl();
18329 
18331  NewPD->setModulePrivate();
18332 
18333  if (NewPD->isInvalidDecl() && PrevDecl) {
18334  // Don't introduce NewFD into scope; there's already something
18335  // with the same name in the same scope.
18336  } else if (II) {
18337  PushOnScopeChains(NewPD, S);
18338  } else
18339  Record->addDecl(NewPD);
18340 
18341  return NewPD;
18342 }
18343 
18345  Declarator &Declarator, unsigned TemplateParameterDepth) {
18346  auto &Info = InventedParameterInfos.emplace_back();
18347  TemplateParameterList *ExplicitParams = nullptr;
18348  ArrayRef<TemplateParameterList *> ExplicitLists =
18350  if (!ExplicitLists.empty()) {
18351  bool IsMemberSpecialization, IsInvalid;
18352  ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18354  Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18355  ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18356  /*SuppressDiagnostic=*/true);
18357  }
18358  if (ExplicitParams) {
18359  Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18360  llvm::append_range(Info.TemplateParams, *ExplicitParams);
18361  Info.NumExplicitTemplateParams = ExplicitParams->size();
18362  } else {
18363  Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18364  Info.NumExplicitTemplateParams = 0;
18365  }
18366 }
18367 
18369  auto &FSI = InventedParameterInfos.back();
18370  if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18371  if (FSI.NumExplicitTemplateParams != 0) {
18372  TemplateParameterList *ExplicitParams =
18376  Context, ExplicitParams->getTemplateLoc(),
18377  ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18378  ExplicitParams->getRAngleLoc(),
18379  ExplicitParams->getRequiresClause()));
18380  } else {
18383  Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18384  SourceLocation(), /*RequiresClause=*/nullptr));
18385  }
18386  }
18387  InventedParameterInfos.pop_back();
18388 }
clang::ASTConsumer::HandleVTable
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:123
clang::FunctionDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4049
clang::Sema::ActOnCXXConditionDeclaration
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
Definition: SemaDeclCXX.cpp:17650
clang::ElaboratedTypeKeyword
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5405
clang::SourceRange::setBegin
void setBegin(SourceLocation b)
Definition: SourceLocation.h:222
clang::NestedNameSpecifier::Create
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Definition: NestedNameSpecifier.cpp:59
clang::ExplicitSpecifier
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1815
TSK_BaseClass
@ TSK_BaseClass
The subobject is a base class.
Definition: SemaDeclCXX.cpp:9647
clang::Sema::CheckShadow
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:7865
clang::TemplateParameterList::getRequiresClause
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:174
clang::DeclSpec::getVirtualSpecLoc
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:579
clang::Declarator::isDeclarationOfFunction
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition: DeclSpec.cpp:325
clang::Language::CUDA
@ CUDA
clang::VirtSpecifiers::isOverrideSpecified
bool isOverrideSpecified() const
Definition: DeclSpec.h:2634
clang::DeclaratorChunk::FunctionTypeInfo::NumParams
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1315
clang::TagDecl::getKindName
StringRef getKindName() const
Definition: Decl.h:3525
extendLeft
static void extendLeft(SourceRange &R, SourceRange Before)
Definition: SemaDeclCXX.cpp:10706
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:950
clang::Sema::SpecialMemberOverloadResult
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:1546
clang::ASTContext::adjustDeducedFunctionResultType
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
Definition: ASTContext.cpp:3133
clang::TemplateSpecializationTypeLoc
Definition: TypeLoc.h:1606
clang::RecordDecl::hasFlexibleArrayMember
bool hasFlexibleArrayMember() const
Definition: Decl.h:3939
clang::UnqualifiedId::TemplateName
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition: DeclSpec.h:997
clang::Sema::CheckDelayedMemberExceptionSpecs
void CheckDelayedMemberExceptionSpecs()
Definition: SemaDeclCXX.cpp:8867
clang::ASTContext::getTypeSizeInChars
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Definition: ASTContext.cpp:2472
clang::CXXConstructorDecl::getExplicitSpecifier
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2495
clang::Sema::BuildDeclarationNameExpr
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3229
PopulateKeysForFields
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
Definition: SemaDeclCXX.cpp:5321
clang::ASTContext::LongDoubleTy
CanQualType LongDoubleTy
Definition: ASTContext.h:1104
BuildBasePathArray
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
Definition: SemaDeclCXX.cpp:2881
clang::Sema::BuildCXXDefaultInitExpr
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaDeclCXX.cpp:15549
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:599
clang::ASTContext::NumImplicitDestructorsDeclared
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3130
clang::DeclSpec::SetTypeQual
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:972
clang::QualType::isMoreQualifiedThan
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:6669
clang::Sema::CCEK_ExplicitBool
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:3867
clang::getComparisonCategoryForBuiltinCmp
Optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
Definition: ComparisonCategories.cpp:24
clang::Sema::VTableUses
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition: Sema.h:7499
CheckConstexprParameterTypes
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
Definition: SemaDeclCXX.cpp:1681
clang::ASTContext::getQualifiedType
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2123
clang::CXXConstructExpr::CK_Complete
@ CK_Complete
Definition: ExprCXX.h:1465
clang::ASTContext::NumImplicitMoveConstructorsDeclared
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3109
clang::FunctionDecl::doesThisDeclarationHaveABody
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2163
clang::Declarator::getName
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1929
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6840
clang::CXXRecordDecl::hasConstexprDefaultConstructor
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition: DeclCXX.h:1225
clang::FunctionTypeLoc::getNumParams
unsigned getNumParams() const
Definition: TypeLoc.h:1458
clang::Sema::isDependentScopeSpecifier
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
Definition: SemaCXXScopeSpec.cpp:167
clang::OpaquePtr::get
PtrTy get() const
Definition: Ownership.h:80
clang::NamespaceDecl::Create
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl)
Definition: DeclCXX.cpp:2857
clang::FunctionDecl::getDefaultedFunctionInfo
DefaultedFunctionInfo * getDefaultedFunctionInfo() const
Definition: Decl.cpp:2968
clang::Decl::getASTContext
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:414
clang::AccessSpecDecl
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
clang::Sema::diagnoseQualifiedDeclaration
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:5848
clang::LookupResult::NotFound
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
clang::InitializedEntity::InitializeMember
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
Definition: Initialization.h:377
clang::FunctionDecl::isDefaulted
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2215
clang::QualType::getObjCLifetime
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1122
clang::Sema::isInitListConstructor
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
Definition: SemaDeclCXX.cpp:11569
buildMemcpyForAssignmentOp
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
Definition: SemaDeclCXX.cpp:14031
clang::QualType::getCVRQualifiers
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6535
clang::TemplateParameterList::Create
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Definition: DeclTemplate.cpp:119
clang::RecordDecl::APK_CanPassInRegs
@ APK_CanPassInRegs
The argument of this type can be passed directly in registers.
Definition: Decl.h:3896
clang::DeclContext::decls_end
decl_iterator decls_end() const
Definition: DeclBase.h:2129
clang::Sema::isCurrentClassNameTypo
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Definition: SemaDeclCXX.cpp:2433
clang::RecordDecl::field_begin
field_iterator field_begin() const
Definition: Decl.cpp:4639
clang::DeducedTemplateSpecializationType
Represents a C++17 deduced template specialization type.
Definition: Type.h:5120
clang::UnqualifiedId::DestructorName
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:994
clang::Sema::LookupNamespaceName
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:4328
clang::DeclContext::removeDecl
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1494
clang::Sema::LookupOverloadedBinOp
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
Definition: SemaOverload.cpp:13510
clang::ParmVarDecl::setUnparsedDefaultArg
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1793
clang::FunctionProtoType::hasTrailingReturn
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:4248
clang::FunctionDecl::setRangeEnd
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2057
clang::CXXRecordDecl::hasUserDeclaredMoveAssignment
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:942
clang::CXXConstructorDecl
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2421
clang::CXXBaseSpecifier::getType
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:245
clang::ASTContext::getTypeDeclType
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1566
clang::CXXMethodDecl::isCopyAssignmentOperator
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2360
clang::Sema::ActOnParamDefaultArgumentError
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
Definition: SemaDeclCXX.cpp:376
clang::VarDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2090
clang::Decl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:416
clang::Declarator::type_objects
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition: DeclSpec.h:2253
clang::SourceRange::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:226
clang::InheritedConstructor::getShadowDecl
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2407
clang::Sema::MatchTemplateParametersToScopeSpecifier
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
Definition: SemaTemplate.cpp:3054
clang::DeclaratorChunk::Array
@ Array
Definition: DeclSpec.h:1177
clang::Sema::UnparsedDefaultArgInstantiations
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:1610
clang::FunctionDecl::getNumParams
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3402
clang::DeclContext::getExternCContext
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1206
clang::IdentifierResolver::AddDecl
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
Definition: IdentifierResolver.cpp:144
clang::LambdaExpr::capture_begin
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
Definition: ExprCXX.cpp:1214
clang::DeclSpec::getRestrictSpecLoc
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:549
clang::DeclContext::decls
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2127
clang::RecordDecl::setArgPassingRestrictions
void setArgPassingRestrictions(ArgPassingKind Kind)
Definition: Decl.h:4043
Specifiers.h
clang::FunctionProtoType::getExceptionSpecType
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4135
getTupleLikeElementType
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
Definition: SemaDeclCXX.cpp:1115
clang::CXXRecordDecl::hasAnyDependentBases
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:566
clang::Sema::ActOnStartDelayedCXXMethodDeclaration
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
Definition: SemaDeclCXX.cpp:10381
clang::Sema::CheckOverloadedOperatorDeclaration
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
Definition: SemaDeclCXX.cpp:15890
clang::CXXRecordDecl::isTriviallyCopyable
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition: DeclCXX.cpp:573
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
clang::UnqualifiedId::TemplateId
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1002
clang::UsingDirectiveDecl::Create
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2818
clang::Sema::DelayedDllExportMemberFunctions
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:13545
clang::Sema::ConditionKind::Boolean
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
clang::Sema::ForVisibleRedeclaration
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:4361
clang::CXXRecordDecl::defaultedCopyConstructorIsDeleted
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:685
clang::OK_Ordinary
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:136
clang::Sema::LoadExternalVTableUses
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
Definition: SemaDeclCXX.cpp:17671
clang::Sema::TUKind
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:1593
IsUsingDirectiveInToplevelContext
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
Definition: SemaDeclCXX.cpp:11587
clang::TypeSourceInfo::getType
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6484
clang::UnqualifiedIdKind::IK_OperatorFunctionId
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
clang::Sema::ActOnTypedefNameDecl
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6438
clang::VirtSpecifiers::getOverrideLoc
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2635
IsEquivalentForUsingDecl
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
Definition: SemaDeclCXX.cpp:11861
clang::CXXMemberCallExpr::getMethodDecl
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition: ExprCXX.cpp:669
clang::LookupResult::setLookupName
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:248
clang::FunctionProtoType::ExceptionSpecInfo::NoexceptExpr
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:3965
clang::Sema::MarkVirtualMemberExceptionSpecsNeeded
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
Definition: SemaDeclCXX.cpp:17847
clang::CXXMethodDecl::isStatic
bool isStatic() const
Definition: DeclCXX.cpp:2092
clang::CXXRecordDecl::setImplicitCopyAssignmentIsDeleted
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition: DeclCXX.h:897
clang::Sema::SubstSpaceshipAsEqualEqual
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
Definition: SemaTemplateInstantiateDecl.cpp:4348
clang::CXXFinalOverriderMap
A mapping from each virtual member function to its set of final overriders.
Definition: CXXInheritance.h:357
clang::Sema::TemplateParameterListsAreEqual
bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Definition: SemaTemplate.cpp:7824
clang::Sema::BuildDeclRefExpr
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2010
clang::TemplateTypeParmDecl::getIndex
unsigned getIndex() const
Retrieve the index of the template parameter.
Definition: DeclTemplate.cpp:682
clang::VarDecl::isInlineSpecified
bool isInlineSpecified() const
Definition: Decl.h:1463
clang::DeclarationName::Identifier
@ Identifier
Definition: DeclarationName.h:201
clang::Sema::LookupLocalFriendName
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:4340
clang::Sema::pushCodeSynthesisContext
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Definition: SemaTemplateInstantiate.cpp:424
clang::UnresolvedSetImpl
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
clang::CXXRecordDecl::hasNonTrivialCopyConstructorForCall
bool hasNonTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1248
clang::FunctionDecl::getReturnType
QualType getReturnType() const
Definition: Decl.h:2541
clang::CharSourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:283
clang::DeclaratorDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:779
clang::Decl::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:420
ImplicitInitializerKind
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
Definition: SemaDeclCXX.cpp:4700
clang::Sema::TypeDiagnoser
Abstract class used to diagnose incomplete types.
Definition: Sema.h:2370
clang::BlockPointerTypeLoc
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1271
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
clang::DeclSpec::TST_enum
static const TST TST_enum
Definition: DeclSpec.h:283
BuildImplicitMemberInitializer
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
Definition: SemaDeclCXX.cpp:4791
AttributeCommonInfo.h
clang::RecordDecl::getArgPassingRestrictions
ArgPassingKind getArgPassingRestrictions() const
Definition: Decl.h:4039
clang::LinkageSpecDecl
Represents a linkage specification.
Definition: DeclCXX.h:2817
clang::DeclContext::addHiddenDecl
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1545
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
clang::Sema::ActOnUsingDirective
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
Definition: SemaDeclCXX.cpp:11644
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
CollectFieldInitializer
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
Definition: SemaDeclCXX.cpp:5055
clang::DecompositionDecl::bindings
ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:4070
clang::VirtSpecifiers::getFinalLoc
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2639
clang::LookupResult::end
iterator end() const
Definition: Lookup.h:336
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1355
clang::Sema::AbstractNone
@ AbstractNone
Definition: Sema.h:7800
clang::PointerTypeLoc
Wrapper for source info for pointers.
Definition: TypeLoc.h:1258
clang::BindingDecl::Create
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3190
clang::LookupResult::setHideTags
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:288
clang::StaticAssertDecl::Create
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:3172
clang::ExplicitSpecKind::Unresolved
@ Unresolved
clang::ASTContext::getDependentNameType
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
Definition: ASTContext.cpp:5023
clang::Sema::ActOnCXXBoolLiteral
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
Definition: SemaExprCXX.cpp:805
checkMoveAssignmentForRepeatedMove
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
Definition: SemaDeclCXX.cpp:14743
clang::CXXConversionDecl
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2751
clang::CXXTryStmt::getNumHandlers
unsigned getNumHandlers() const
Definition: StmtCXX.h:106
clang::TargetInfo::CCK_ClangABI4OrPS4
@ CCK_ClangABI4OrPS4
Definition: TargetInfo.h:1524
clang::Sema::ActOnStartLinkageSpecification
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
Definition: SemaDeclCXX.cpp:16277
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:541
clang::VarDecl::hasGlobalStorage
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1142
clang::LookupResult::isSingleResult
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:308
clang::CXXRecordDecl::setHasTrivialSpecialMemberForCall
void setHasTrivialSpecialMemberForCall()
Definition: DeclCXX.h:1339
clang::TypoCorrection
Simple class containing the result of Sema::CorrectTypo.
Definition: TypoCorrection.h:42
clang::transformer::access
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
clang::Sema::UPPC_DeclarationType
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:8447
clang::FixItHint::CreateInsertion
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
clang::NamespaceAliasDecl
Represents a C++ namespace alias.
Definition: DeclCXX.h:3006
clang::Sema::ActOnParamDefaultArgument
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
Definition: SemaDeclCXX.cpp:308
clang::Sema::DiagnoseSentinelCalls
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:443
clang::UnionOpaquePtr::get
OpaquePtr< T > get() const
Definition: Ownership.h:104
clang::Sema::DeclareImplicitMoveConstructor
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
Definition: SemaDeclCXX.cpp:15180
clang::TypoCorrection::getCorrectionSpecifier
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Definition: TypoCorrection.h:91
clang::ParsedAttr::isDeclspecPropertyAttribute
bool isDeclspecPropertyAttribute() const
Is this the Microsoft __declspec(property) attribute?
Definition: ParsedAttr.h:467
clang::ObjCImplementationDecl
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2545
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1781
clang::DeclSpec::getExplicitSpecLoc
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:584
clang::Sema::ActOnFinishCXXNonNestedClass
void ActOnFinishCXXNonNestedClass()
Definition: SemaDeclCXX.cpp:13836
clang::ReferenceTypeLoc
Definition: TypeLoc.h:1339
clang::EnumDecl::enumerators
enumerator_range enumerators() const
Definition: Decl.h:3745
clang::NestedNameSpecifier::isDependent
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
Definition: NestedNameSpecifier.cpp:234
clang::Decl::isTemplateParameter
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2552
clang::QualType::isConstQualified
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6561
clang::Sema::SemaDiagnosticBuilder::Kind
Kind
Definition: Sema.h:1942
clang::ConstantArrayType
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2944
clang::Declarator::getNumTypeObjects
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2236
clang::Sema::SourceMgr
SourceManager & SourceMgr
Definition: Sema.h:590
clang::Sema::getTrivialTemplateArgumentLoc
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
Definition: SemaTemplateDeduction.cpp:2496
clang::ExplicitSpecKind::ResolvedFalse
@ ResolvedFalse
clang::FunctionDecl::isConstexpr
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2283
clang::DeclSpec::getExplicitSpecRange
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:585
clang::Decl::isOutOfLine
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
GetKeyForMember
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
Definition: SemaDeclCXX.cpp:5337
clang::DeclaratorChunk::FunctionTypeInfo::hasMethodTypeQualifiers
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1473
clang::LookupResult::FoundOverloaded
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
clang::FieldDecl::setInClassInitializer
void setInClassInitializer(Expr *Init)
Set the C++11 in-class initializer for this member.
Definition: Decl.h:2996
clang::ASTContext::NumImplicitDefaultConstructors
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3091
clang::LookupResult::Filter::next
NamedDecl * next()
Definition: Lookup.h:643
clang::SourceManager::isInMainFile
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Definition: SourceManager.cpp:1591
clang::ExplicitSpecifier::setExpr
void setExpr(Expr *E)
Definition: DeclCXX.h:1849
clang::FunctionDecl::isDeleted
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2338
clang::DeclSpec::isInlineSpecified
bool isInlineSpecified() const
Definition: DeclSpec.h:567
clang::UsingDecl::getQualifier
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3436
clang::Sema::checkDeclIsAllowedInOpenMPTarget
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
Definition: SemaOpenMP.cpp:22069
clang::DeclSpec::getAttributes
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:795
clang::TagDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4325
clang::CXXBasePath::Decls
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
Definition: CXXInheritance.h:80
clang::UnaryOperator::Create
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4597
checkCUDADeviceBuiltinTextureClassTemplate
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
Definition: SemaDeclCXX.cpp:6223
clang::Qualifiers::OCL_Weak
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
SemaInternal.h
clang::UsingDirectiveDecl
Represents C++ using-directive.
Definition: DeclCXX.h:2902
clang::Sema::ActOnCXXExitDeclInitializer
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
Definition: SemaDeclCXX.cpp:17635
clang::Sema::RequireCompleteDeclContext
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
Definition: SemaCXXScopeSpec.cpp:199
clang::ConstantArrayType::getSize
const llvm::APInt & getSize() const
Definition: Type.h:2967
clang::CXXRecordDecl::hasVariantMembers
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1191
clang::Sema::MergeVarDeclExceptionSpecs
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
Definition: SemaDeclCXX.cpp:1544
clang::Sema::NoteDeletedFunction
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:110
clang::BindingDecl
A binding in a decomposition declaration.
Definition: DeclCXX.h:3979
clang::Sema::forRedeclarationInCurContext
RedeclarationKind forRedeclarationInCurContext()
Definition: Sema.h:4368
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1092
clang::DeclarationName::CXXConstructorName
@ CXXConstructorName
Definition: DeclarationName.h:204
clang::DeclSpec::SCS_static
@ SCS_static
Definition: DeclSpec.h:237
clang::Sema::InventedParameterInfos
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition: Sema.h:977
clang::Sema::CheckOverridingFunctionExceptionSpec
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Definition: SemaExceptionSpec.cpp:960
clang::ComparisonCategoryInfo::ValueInfo::hasValidIntValue
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
Definition: ComparisonCategories.cpp:43
llvm::SmallVector< StringRef, 8 >
Lookup.h
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:596
clang::Declarator::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1945
clang::RecordDecl::field_empty
bool field_empty() const
Definition: Decl.h:4113
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: RecursiveASTVisitor.h:1009
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::Sema::CodeSynthesisContext::PointOfInstantiation
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:9149
functionDeclHasDefaultArgument
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
Definition: SemaDeclCXX.cpp:438
clang::Sema::CheckFriendAccess
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
Definition: SemaAccess.cpp:1806
clang::Qualifiers::removeAddressSpace
void removeAddressSpace()
Definition: Type.h:388
clang::QualType::getQualifiers
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6529
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:138
clang::ASTContext::getIntWidth
unsigned getIntWidth(QualType T) const
Definition: ASTContext.cpp:10696
clang::ActionResult::getAs
T * getAs()
Definition: Ownership.h:170
clang::Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
@ NoMemberOrDeleted
Definition: Sema.h:1549
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:915
clang::ComparisonCategoryInfo::ValueInfo::VD
VarDecl * VD
Definition: ComparisonCategories.h:86
clang::TTK_Struct
@ TTK_Struct
The "struct" keyword.
Definition: Type.h:5388
clang::FunctionDecl::hasOneParamOrDefaultArgs
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3441
clang::Sema::LookupOverloadedOperatorName
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
Definition: SemaLookup.cpp:3112
clang::TargetCXXABI::hasKeyFunctions
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:208
clang::DeclSpec::TST_error
static const TST TST_error
Definition: DeclSpec.h:301
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:247
clang::Decl::ModuleOwnershipKind::ModulePrivate
@ ModulePrivate
This declaration has an owning module, but is only visible to lookups that occur within that module.
clang::ParenListExpr
Definition: Expr.h:5590
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::ClassTemplateSpecializationDecl::getPointOfInstantiation
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
Definition: DeclTemplate.h:1940
clang::RecordDecl::field_iterator
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4102
clang::AS_private
@ AS_private
Definition: Specifiers.h:111
clang::VarDecl::setInit
void setInit(Expr *I)
Definition: Decl.cpp:2355
clang::DeclaratorChunk::MemberPointer
@ MemberPointer
Definition: DeclSpec.h:1177
clang::Attr::getLocation
SourceLocation getLocation() const
Definition: Attr.h:91
clang::UnqualifiedIdKind::IK_DeductionGuideName
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
clang::ClassTemplateSpecializationDecl::getSpecializedTemplate
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Definition: DeclTemplate.cpp:965
clang::Sema::ComparisonCategoryUsage
ComparisonCategoryUsage
Definition: Sema.h:6072
clang::OR_Success
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:53
EvaluatedExprVisitor.h
clang::ParmVarDecl::getDefaultArgRange
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2840
TargetInfo.h
clang::NamedDecl::getUnderlyingDecl
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:458
clang::MultiVersionKind::Target
@ Target
clang::LookupResult::clear
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:554
clang::Sema::findInheritingConstructor
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
Definition: SemaDeclCXX.cpp:13522
clang::QualType::getNonReferenceType
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6698
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3582
CXXInheritance.h
clang::Sema::DefineInheritingConstructor
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
Definition: SemaDeclCXX.cpp:13612
clang::ConstructorUsingShadowDecl::getParent
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition: DeclCXX.h:3548
clang::Sema::ActOnMemInitializers
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
Definition: SemaDeclCXX.cpp:5556
clang::DeclSpec::getRepAsExpr
Expr * getRepAsExpr() const
Definition: DeclSpec.h:494
clang::ASTContext::DeclarationNames
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:655
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:324
clang::Sema::GatherArgumentsForCall
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:6136
clang::Sema::CXXDefaultConstructor
@ CXXDefaultConstructor
Definition: Sema.h:1670
clang::TSK_Undeclared
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:176
clang::CXXRecordDecl::getDefinition
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:542
clang::Sema::SetDeclDefaulted
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
Definition: SemaDeclCXX.cpp:17306
clang::FunctionDecl::getCanonicalDecl
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3327
clang::MultiExprArg
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:272
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:675
clang::Sema::DiagnoseAbstractType
void DiagnoseAbstractType(const CXXRecordDecl *RD)
Definition: SemaDeclCXX.cpp:5804
clang::TypeDecl::getTypeForDecl
const Type * getTypeForDecl() const
Definition: Decl.h:3166
clang::NonTypeTemplateParmDecl
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Definition: DeclTemplate.h:1384
clang::TemplateName::getAsTemplateDecl
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
Definition: TemplateName.cpp:101
clang::FunctionDecl::getParamDecl
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2510
clang::FunctionDefinitionKind::Deleted
@ Deleted
clang::Declarator::getIdentifier
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2188
clang::Sema::AR_accessible
@ AR_accessible
Definition: Sema.h:7715
clang::EST_None
@ EST_None
no exception specification
Definition: ExceptionSpecificationType.h:21
clang::DeclarationNameInfo::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclarationName.h:865
clang::NestedNameSpecifier
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Definition: NestedNameSpecifier.h:50
clang::DynamicInitKind::Initializer
@ Initializer
clang::DecompositionDeclarator::bindings
ArrayRef< Binding > bindings() const
Definition: DeclSpec.h:1739
clang::getDLLAttr
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
clang::Sema::ActOnCXXEnterDeclInitializer
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
Definition: SemaDeclCXX.cpp:17614
clang::FunctionDecl::willHaveBody
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2431
clang::DeclaratorChunk::Reference
@ Reference
Definition: DeclSpec.h:1177
clang::TypoCorrection::getCorrectionDeclAs
DeclClass * getCorrectionDeclAs() const
Definition: TypoCorrection.h:156
clang::ComparisonCategories::getInfoForType
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
Definition: ComparisonCategories.cpp:160
clang::UnresolvedSetIterator
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
clang::CXXRecordDecl::MergeAccess
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1672
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2839
clang::Sema::StdBadAlloc
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:1296
clang::ClassTemplateSpecializationDecl::getSpecializationKind
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Definition: DeclTemplate.h:1901
clang::FunctionProtoType::ExtProtoInfo::RefQualifier
RefQualifierKind RefQualifier
Definition: Type.h:3988
clang::Sema::FilterLookupForScope
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1578
clang::DeclaratorChunk::Fun
FunctionTypeInfo Fun
Definition: DeclSpec.h:1552
clang::EST_Dynamic
@ EST_Dynamic
throw(T1, T2)
Definition: ExceptionSpecificationType.h:23
clang::Sema::ActOnNamespaceAliasDef
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
Definition: SemaDeclCXX.cpp:13104
clang::LookupResult
Represents the results of name lookup.
Definition: Lookup.h:46
clang::ASTContext::getBaseElementType
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Definition: ASTContext.cpp:6789
clang::FieldDecl::getInClassInitializer
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.h:2986
clang::Qualifiers
The collection of all-type qualifiers we support.
Definition: Type.h:147
clang::Sema::BuildMemberReferenceExpr
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
Definition: SemaExprMember.cpp:743
clang::Sema::CheckDestructor
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
Definition: SemaDeclCXX.cpp:10551
clang::DeclListNode::iterator
Definition: DeclBase.h:1252
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1233
clang::Declarator::getContext
DeclaratorContext getContext() const
Definition: DeclSpec.h:1935
clang::SourceManager::getImmediateExpansionRange
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
Definition: SourceManager.cpp:1024
clang::Sema::DeclareImplicitDefaultConstructor
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
Definition: SemaDeclCXX.cpp:13408
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1664
clang::Sema::Diag
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1960
clang::Sema::GetTypeForDeclarator
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5812
clang::Redeclarable::getFirstDecl
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
clang::Sema::TUScope
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1289
clang::ParmVarDecl::getDefaultArg
Expr * getDefaultArg()
Definition: Decl.cpp:2823
clang::DeclRefExpr::isNonOdrUse
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1419
memcpy
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Definition: __clang_cuda_device_functions.h:1549
clang::VK_XValue
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:129
clang::TagDecl::getCanonicalDecl
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4331
clang::TemplateParameterList::getLAngleLoc
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:194
int
__device__ int
Definition: __clang_hip_libdevice_declares.h:63
clang::ASTContext::getFunctionType
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1544
clang::Decl::isUsed
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:443
clang::UnqualifiedIdKind::IK_Identifier
@ IK_Identifier
An identifier.
clang::DeclaratorChunk::Pipe
@ Pipe
Definition: DeclSpec.h:1177
clang::Type::getContainedDeducedType
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1889
clang::CXXMethodDecl::getCanonicalDecl
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2053
clang::Sema::VerifyIntegerConstantExpression
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:16814
clang::MSPropertyDecl::Create
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3254
clang::LookupResult::NotFoundInCurrentInstantiation
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
clang::TargetInfo::getCallingConvKind
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:496
clang::Sema::CodeSynthesisContexts
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:9202
clang::Sema::Ovl_NonFunction
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:3769
clang::Sema::checkClassLevelCodeSegAttribute
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
Definition: SemaDeclCXX.cpp:6286
clang::Sema::DefaultedComparisonKind::Relational
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
clang::TemplateSubstitutionKind::Specialization
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
clang::FunctionProtoType::ExtProtoInfo::Variadic
bool Variadic
Definition: Type.h:3985
clang::UsingShadowDecl
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3207
clang::Sema::DiscardCleanupsInEvaluationContext
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17368
clang::TemplateSpecializationType
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5181
clang::FunctionDecl::isOverloadedOperator
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2629
clang::Type::containsUnexpandedParameterPack
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1880
clang::IfStmt
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1909
clang::SourceRange::isValid
bool isValid() const
Definition: SourceLocation.h:225
clang::Decl::getIdentifierNamespace
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:822
clang::Sema::CreateBuiltinBinOp
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:14559
clang::Sema::getSourceManager
SourceManager & getSourceManager() const
Definition: Sema.h:1779
clang::Decl::isTemplateParameterPack
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:201
clang::DeclarationNameTable::getCXXDestructorName
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
Definition: DeclarationName.cpp:326
clang::Sema::CheckTemplateIdType
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Definition: SemaTemplate.cpp:3651
clang::Type::isRealFloatingType
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2138
clang::Sema::AR_dependent
@ AR_dependent
Definition: Sema.h:7717
clang::Sema::LookupQualifiedName
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Definition: SemaLookup.cpp:2223
clang::DeclSpec::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:506
clang::CXXRecordDecl::hasTrivialDestructorForCall
bool hasTrivialDestructorForCall() const
Definition: DeclCXX.h:1325
clang::FunctionDecl::getPrimaryTemplate
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3834
clang::ComplexType::getElementType
QualType getElementType() const
Definition: Type.h:2612
clang::InitListExpr
Describes an C or C++ initializer list.
Definition: Expr.h:4844
distance
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
AddInitializerToDiag
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
Definition: SemaDeclCXX.cpp:5345
clang::ASTContext::NumImplicitCopyConstructorsDeclared
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3102
clang::DeclSpec::SCS_unspecified
@ SCS_unspecified
Definition: DeclSpec.h:234
clang::FunctionDecl::getDeclaredReturnType
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2558
llvm::Optional
Definition: LLVM.h:40
clang::Sema::AbstractFieldType
@ AbstractFieldType
Definition: Sema.h:7804
clang::Sema::BuildCXXConstructExpr
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
Definition: SemaDeclCXX.cpp:15445
clang::ComparisonCategoryType::First
@ First
clang::LambdaExpr::capture_end
capture_iterator capture_end() const
Retrieve an iterator pointing past the end of the sequence of lambda captures.
Definition: ExprCXX.cpp:1218
clang::RecordDecl::getDefinition
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4090
clang::DeclSpec::hasExplicitSpecifier
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:581
clang::Sema::BuildBasePathArray
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
Definition: SemaDeclCXX.cpp:2900
clang::TypeLoc::getEndLoc
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:228
clang::ActionResult::isUnset
bool isUnset() const
Definition: Ownership.h:167
clang::Sema::ActOnFields
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:17564
llvm::SmallPtrSet
Definition: ASTContext.h:82
clang::Lexer::getSourceText
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:962
clang::UnaryOperator
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2215
clang::DeclSpec::TQ_volatile
@ TQ_volatile
Definition: DeclSpec.h:308
clang::Expr::isPRValue
bool isPRValue() const
Definition: Expr.h:271
clang::Sema::ConditionResult::isInvalid
bool isInvalid() const
Definition: Sema.h:12548
clang::QualType::getAsString
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1017
clang::prec::Assignment
@ Assignment
Definition: OperatorPrecedence.h:29
clang::Scope::AddDecl
void AddDecl(Decl *D)
Definition: Scope.h:306
clang::Sema::ActOnReenterCXXMethodParameter
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
Definition: SemaDeclCXX.cpp:10364
clang::DeclarationNameInfo::containsUnexpandedParameterPack
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
Definition: DeclarationName.cpp:413
clang::FunctionDecl::setDefaulted
void setDefaulted(bool D=true)
Definition: Decl.h:2216
clang::Sema::CheckCompletedCXXClass
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
Definition: SemaDeclCXX.cpp:6753
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:7057
clang::InitializationKind::CreateDirect
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
Definition: Initialization.h:627
clang::CXXRecordDecl::isGenericLambda
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1480
clang::FunctionDecl::isUserProvided
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2230
clang::Sema::ActOnFinishCXXInClassMemberInitializer
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
Definition: SemaDeclCXX.cpp:4050
clang::FunctionDecl::getTemplateSpecializationArgs
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3850
clang::Sema::DefineImplicitCopyConstructor
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
Definition: SemaDeclCXX.cpp:15132
clang::QualType::isVolatileQualified
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6572
clang::CXXRecordDecl::hasUserDeclaredConstructor
bool hasUserDeclaredConstructor() const
Determine whether this class has any user-declared constructors.
Definition: DeclCXX.h:768
clang::Sema::ActOnFinishTrailingRequiresClause
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
Definition: SemaDeclCXX.cpp:4028
clang::EST_Unparsed
@ EST_Unparsed
not parsed yet
Definition: ExceptionSpecificationType.h:32
clang::OverridingMethods::const_iterator
MapType::const_iterator const_iterator
Definition: CXXInheritance.h:278
findCircularInheritance
static bool findCircularInheritance(const CXXRecordDecl *Class, const CXXRecordDecl *Current)
Determine whether the given class is a base class of the given class, including looking at dependent ...
Definition: SemaDeclCXX.cpp:2458
clang::Sema::isEquivalentInternalLinkageDeclaration
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
Definition: SemaOverload.cpp:9974
clang::CPlusPlus14
@ CPlusPlus14
Definition: LangStandard.h:50
clang::Sema::BuildCallExpr
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6656
DeclSpec.h
clang::CXXTryStmt::getHandler
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:107
clang::ASTContext::Char8Ty
CanQualType Char8Ty
Definition: ASTContext.h:1098
clang::Decl::getAttr
T * getAttr() const
Definition: DeclBase.h:537
clang::ArrayTypeLoc::getElementLoc
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1549
CastForMoving
static Expr * CastForMoving(Sema &SemaRef, Expr *E, QualType T=QualType())
Definition: SemaDeclCXX.cpp:4685
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:64
clang::Sema::ActOnFinishFunctionDeclarationDeclarator
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
Definition: SemaDeclCXX.cpp:18368
clang::isComputedNoexcept
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
Definition: ExceptionSpecificationType.h:39
clang::Sema::IsOverload
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs=true, bool ConsiderRequiresClauses=true)
Definition: SemaOverload.cpp:1141
clang::InitializedEntity::InitializeParameter
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
Definition: Initialization.h:253
clang::ParsedAttributesView::end
iterator end()
Definition: ParsedAttr.h:970
clang::DeclSpec::TQ_unaligned
@ TQ_unaligned
Definition: DeclSpec.h:309
clang::PrintingPolicy
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
clang::RecordDecl::APK_CanNeverPassInRegs
@ APK_CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition: Decl.h:3910
clang::Sema::GetNameFromUnqualifiedId
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5540
clang::Sema::BuildCallToMemberFunction
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
Definition: SemaOverload.cpp:14314
clang::BinaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:3905
clang::DeclSpec::TQ_atomic
@ TQ_atomic
Definition: DeclSpec.h:312
clang::IdentifierResolver::RemoveDecl
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
Definition: IdentifierResolver.cpp:209
ASTLambda.h
clang::DeclarationName::getAsIdentifierInfo
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
Definition: DeclarationName.h:408
clang::TemplateSpecializationTypeLoc::getArgLoc
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1648
clang::FunctionDecl::isInlineSpecified
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2595
clang::ASTContext::getCurrentKeyFunction
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
Definition: RecordLayoutBuilder.cpp:3364
clang::Type::isRValueReferenceType
bool isRValueReferenceType() const
Definition: Type.h:6770
clang::Sema::getStdNamespace
NamespaceDecl * getStdNamespace() const
Definition: SemaDeclCXX.cpp:11287
clang::DeclSpec::getConstSpecLoc
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:548
clang::Sema::AbstractParamType
@ AbstractParamType
Definition: Sema.h:7802
clang::ParsedAttributesView::hasAttribute
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:990
clang::getRewrittenOverloadedOperator
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
clang::FunctionDecl::setDeletedAsWritten
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2346
clang::DeclContext::getLexicalParent
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1888
clang::Sema::BuildMemberInitializer
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
Definition: SemaDeclCXX.cpp:4398
clang::InitializationSequence
Describes the sequence of initializations required to initialize a given object or reference with a s...
Definition: Initialization.h:788
clang::Sema::CheckConversionDeclarator
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
Definition: SemaDeclCXX.cpp:10728
clang::Sema::DiagnoseHiddenVirtualMethods
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
Definition: SemaDeclCXX.cpp:10028
clang::FunctionType
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3561
clang::tooling::fixit::internal::getSourceRange
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
clang::Declarator::isDecompositionDeclarator
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2184
checkLiteralOperatorTemplateParameterList
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
Definition: SemaDeclCXX.cpp:16047
getTrivialTypeTemplateArgument
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaDeclCXX.cpp:1062
clang::Sema::PopDeclContext
void PopDeclContext()
Definition: SemaDecl.cpp:1312
clang::CXXRecordDecl::friends
friend_range friends() const
Definition: DeclFriend.h:247
checkMemberDecomposition
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
Definition: SemaDeclCXX.cpp:1370
clang::ExternalSemaSource::ReadUsedVTables
virtual void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables)
Read the set of used vtables known to the external Sema source.
Definition: ExternalSemaSource.h:171
clang::TTK_Interface
@ TTK_Interface
The "__interface" keyword.
Definition: Type.h:5391
clang::Sema::DiagnoseClassNameShadow
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:5817
clang::CXXRecordDecl::lookupInBases
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
Definition: CXXInheritance.cpp:307
LiteralSupport.h
ReportOverrides
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
Definition: SemaDeclCXX.cpp:6731
clang::DeclSpec::getSpecifierName
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:542
Bindings
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
Definition: RetainCountDiagnostics.cpp:616
FindBaseInitializer
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
Definition: SemaDeclCXX.cpp:4108
clang::Sema::FindDeallocationFunction
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true)
Definition: SemaExprCXX.cpp:3182
clang::FunctionDecl::param_size
size_t param_size() const
Definition: Decl.h:2503
clang::DeclarationName
The name of a declaration.
Definition: DeclarationName.h:143
clang::Type::isElaboratedTypeSpecifier
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:2936
clang::RecordDecl::isInjectedClassName
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:4605
clang::ASTContext::getTranslationUnitDecl
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1074
clang::index::SymbolKind::Constructor
@ Constructor
clang::LookupResult::begin
iterator begin() const
Definition: Lookup.h:335
clang::ASTContext::Char16Ty
CanQualType Char16Ty
Definition: ASTContext.h:1099
clang::TemplateArgumentLoc::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:514
clang::Sema::EnterTemplatedContext
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1388
clang::Sema::VTablesUsed
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition: Sema.h:7505
clang::Sema::CompoundScopeRAII
A RAII object to enter scope of a compound statement.
Definition: Sema.h:5014
clang::DeclContextLookupResult::begin
iterator begin()
Definition: DeclBase.h:1314
clang::CXXRecordDecl::hasInClassInitializer
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1110
clang::Sema::AR_delayed
@ AR_delayed
Definition: Sema.h:7718
clang::Decl::isLocalExternDecl
bool isLocalExternDecl()
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1100
clang::Decl::markUsed
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:458
clang::StringLiteralParser::isValidUDSuffix
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
Definition: LiteralSupport.cpp:2142
clang::Declarator::getIdentifierLoc
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2194
clang::CXXRecordDecl::needsOverloadResolutionForMoveAssignment
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:975
clang::CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable
bool lambdaIsDefaultConstructibleAndAssignable() const
Determine whether this lambda should have an implicit default constructor and copy and move assignmen...
Definition: DeclCXX.cpp:676
clang::ASTContext::NumImplicitCopyConstructors
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3098
clang::Preprocessor::getIdentifierTable
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:992
clang::Sema::isUnevaluatedContext
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:9508
clang::DeclSpec::getTypeSpecTypeLoc
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:514
clang::Sema::DeclareImplicitMoveAssignment
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
Definition: SemaDeclCXX.cpp:14663
clang::DeclSpec::getFriendSpecLoc
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:749
clang::ObjCImplDecl::getClassInterface
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2433
clang::Sema::ActOnFinishLinkageSpecification
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
Definition: SemaDeclCXX.cpp:16330
clang::DeclaratorChunk::Paren
@ Paren
Definition: DeclSpec.h:1177
clang::OverloadCandidateSet::OperatorRewriteInfo
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:961
clang::DependentNameTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2328
clang::Sema::CheckOverridingFunctionReturnType
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
Definition: SemaDeclCXX.cpp:17462
clang::ASTContext::hasSameTemplateName
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
Definition: ASTContext.cpp:6188
clang::Scope::getParent
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:234
clang::Sema::MarkVirtualBaseDestructorsReferenced
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const RecordType * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
Definition: SemaDeclCXX.cpp:5723
clang::FunctionDecl::isConsteval
bool isConsteval() const
Definition: Decl.h:2295
clang::CXXRecordDecl::getLambdaCallOperator
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1511
clang::EnumDecl
Represents an enum.
Definition: Decl.h:3612
clang::Sema::ActOnUsingDeclaration
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
Definition: SemaDeclCXX.cpp:11740
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1135
clang::CXXMethodDecl::isMoveAssignmentOperator
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2381
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:587
clang::FunctionProtoType::ExceptionSpecInfo::SourceDecl
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:3969
ComputeDefaultedSpecialMemberExceptionSpec
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, Sema::InheritedConstructorInfo *ICI)
Definition: SemaDeclCXX.cpp:13279
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1492
Preprocessor.h
clang::UsingShadowDecl::getTargetDecl
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3271
getRecordDiagFromTagKind
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
Definition: SemaDeclCXX.cpp:1716
clang::Sema::UPPC_ExceptionType
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:8483
clang::FunctionDecl::isInlined
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2617
clang::Sema::BuildFieldReferenceExpr
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
Definition: SemaExprMember.cpp:1782
clang::DeclContext::getNonTransparentContext
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1232
clang::Sema::FieldCollector
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:999
clang::TU_Prefix
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:763
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:278
specialMemberIsConstexpr
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
Definition: SemaDeclCXX.cpp:7189
clang::CXXCtorInitializer::getSourceLocation
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2540
clang::LookupResult::addDecl
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:426
clang::ConditionalOperator
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4199
clang::ObjCImplementationDecl::setIvarInitializers
void setIvarInitializers(ASTContext &C, CXXCtorInitializer **initializers, unsigned numInitializers)
Definition: DeclObjC.cpp:2242
clang::TypedefType
Definition: Type.h:4407
clang::CXXScopeSpec::clear
void clear()
Definition: DeclSpec.h:212
clang::Type::containsErrors
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2177
clang::FunctionDecl::isVirtualAsWritten
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2181
clang::driver::tools::arm::ReadTPMode::Invalid
@ Invalid
clang::Sema::MakeFullDiscardedValueExpr
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:4994
clang::Sema::DefineImplicitDestructor
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
Definition: SemaDeclCXX.cpp:13761
clang::UnqualifiedId::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1162
clang::Sema::PushNamespaceVisibilityAttr
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
Definition: SemaAttr.cpp:1211
clang::FriendTemplateDecl::Create
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
Definition: DeclTemplate.cpp:1098
clang::CXXMethodDecl::Create
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2180
lookupCallFromSpecialMember
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
Definition: SemaDeclCXX.cpp:7084
clang::Sema::MarkVirtualMembersReferenced
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
Definition: SemaDeclCXX.cpp:17854
clang::Sema::inferCUDATargetForImplicitSpecialMember
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:324
checkMethodTypeQualifiers
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
Definition: SemaDeclCXX.cpp:10428
clang::Sema::checkInitializerLifetime
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
Definition: SemaInit.cpp:7544
clang::CXXRecordDecl::setImplicitMoveConstructorIsDeleted
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:855
clang::CXXScopeSpec::isSet
bool isSet() const
Deprecated.
Definition: DeclSpec.h:210
clang::AS_none
@ AS_none
Definition: Specifiers.h:112
clang::AccessSpecDecl::Create
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:117
clang::LinkageSpecDecl::lang_c
@ lang_c
Definition: DeclCXX.h:2826
clang::ParenListExpr::Create
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4482
clang::Sema::checkClassLevelDLLAttribute
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
Definition: SemaDeclCXX.cpp:6297
clang::Sema::getAmbiguousPathsDisplayString
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
Definition: SemaDeclCXX.cpp:3024
clang::TypeLoc::getBeginLoc
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:191
clang::CPlusPlus17
@ CPlusPlus17
Definition: LangStandard.h:51
clang::Sema::AddPragmaAttributes
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1013
clang::ObjCRuntime::isFragile
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
clang::FixItHint
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
clang::InheritableAttr
Definition: Attr.h:140
clang::Sema::CheckExplicitlyDefaultedComparison
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
Definition: SemaDeclCXX.cpp:8500
clang::Sema::CXXMoveConstructor
@ CXXMoveConstructor
Definition: Sema.h:1672
clang::Diagnostic
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1553
clang::AttributeCommonInfo::AS_Keyword
@ AS_Keyword
__ptr16, alignas(...), etc.
Definition: AttributeCommonInfo.h:42
clang::Sema::getLangOpts
const LangOptions & getLangOpts() const
Definition: Sema.h:1774
clang::CXXConstructorDecl::Create
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2604
clang::Sema::CheckConstructor
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
Definition: SemaDeclCXX.cpp:10516
clang::EST_DependentNoexcept
@ EST_DependentNoexcept
noexcept(expression), value-dependent
Definition: ExceptionSpecificationType.h:27
clang::Sema::NoteHiddenVirtualMethods
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Definition: SemaDeclCXX.cpp:10015
clang::ReferenceType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2784
clang::FunctionTypeLoc
Wrapper for source info for functions.
Definition: TypeLoc.h:1383
clang::Qualifiers::getAddressSpace
LangAS getAddressSpace() const
Definition: Type.h:363
clang::Sema::ActOnStartFunctionDeclarationDeclarator
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
Definition: SemaDeclCXX.cpp:18344
clang::EST_Unevaluated
@ EST_Unevaluated
not evaluated yet, for special member function
Definition: ExceptionSpecificationType.h:30
clang::Declarator::getDeclSpec
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1910
clang::CXXRecordDecl::getDescribedClassTemplate
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1810
clang::Sema::DefaultedComparisonKind::Equal
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
clang::TypeAliasTemplateDecl::getTemplatedDecl
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:2541
clang::CanQual::getTypePtr
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
clang::StructuralEquivalenceKind::Default
@ Default
APSInt
llvm::APSInt APSInt
Definition: ByteCodeEmitter.cpp:19
clang::CXXThisExpr::getLocation
SourceLocation getLocation() const
Definition: ExprCXX.h:1153
clang::Redeclarable::setPreviousDecl
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4634
clang::CXXDefaultInitExpr::Create
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext)
Field is the non-static data member whose default initializer is used by this expression.
Definition: ExprCXX.h:1336
clang::LookupResult::resolveKind
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:482
clang::EST_NoexceptTrue
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
Definition: ExceptionSpecificationType.h:29
clang::UnresolvedUsingTypenameDecl
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3829
clang::Declarator::setInventedTemplateParameterList
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition: DeclSpec.h:2496
clang::ParmVarDecl::setScopeInfo
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1697
clang::Sema::CheckForFunctionRedefinition
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:14333
clang::IdentifierInfo::isStr
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Definition: IdentifierTable.h:176
clang::Decl::getLexicalDeclContext
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:851
clang::Sema::ActOnTag
Decl * ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:15836
clang::Sema::LookupMemberName
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:4313
clang::Type::isLiteralType
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2566
clang::VarDecl::isParameterPack
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2554
clang::FunctionTemplateDecl
Declaration of a template function.
Definition: DeclTemplate.h:979
clang::Sema::RequireCompleteType
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8601
clang::CXXRecordDecl::vbases_begin
base_class_iterator vbases_begin()
Definition: DeclCXX.h:620
llvm::MutableArrayRef
Definition: LLVM.h:35
clang::Sema::CXXDestructor
@ CXXDestructor
Definition: Sema.h:1675
clang::Sema::CheckDerivedToBaseConversion
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Definition: SemaDeclCXX.cpp:3001
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6762
clang::Sema::TAH_IgnoreTrivialABI
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:3439
clang::FunctionDecl::setConstexprKind
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2286
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:3003
clang::DeclStmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1323
SearchForReturnInStmt
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
Definition: SemaDeclCXX.cpp:17395
clang::TSK_ExplicitInstantiationDeclaration
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:187
V
#define V(N, I)
Definition: ASTContext.h:3167
findDecomposableBaseClass
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
Definition: SemaDeclCXX.cpp:1299
clang::AttributeCommonInfo::UnknownAttribute
@ UnknownAttribute
Definition: AttributeCommonInfo.h:58
clang::ASTContext::getExternalSource
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1180
clang::QualType::hasNonTrivialObjCLifetime
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1126
Template.h
clang::LangOptions::isCompatibleWithMSVC
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:464
clang::TranslationUnitDecl
The top declaration context.
Definition: Decl.h:80
clang::Sema::getShadowedDeclaration
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:7831
clang::VirtSpecifiers::isFinalSpecified
bool isFinalSpecified() const
Definition: DeclSpec.h:2637
clang::Decl::Kind
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:86
clang::InheritableAttr::setInherited
void setInherited(bool I)
Definition: Attr.h:150
clang::NestedNameSpecifier::containsUnexpandedParameterPack
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
Definition: NestedNameSpecifier.cpp:242
clang::Sema::getTemplateInstantiationArgs
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const TemplateArgumentList *Innermost=nullptr, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
Definition: SemaTemplateInstantiate.cpp:58
clang::Expr::isTypeDependent
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:185
clang::Sema::DelayedOverridingExceptionSpecChecks
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition: Sema.h:1063
clang::FunctionDecl::getConstexprKind
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2289
clang::CXXRecordDecl::hasUserDeclaredMoveConstructor
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:834
clang::RecordType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4649
clang::TemplateArgument::getKind
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:244
clang::Sema::AttachBaseSpecifiers
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
Definition: SemaDeclCXX.cpp:2716
clang::DeclSpec::getVolatileSpecLoc
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:550
findUserDeclaredCtor
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
Definition: SemaDeclCXX.cpp:9627
clang::CompoundStmt
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1404
clang::Sema::BuildCXXNamedCast
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition: SemaCast.cpp:297
clang::Sema::CheckOverload
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl)
Determine whether the given New declaration is an overload of the declarations in Old.
Definition: SemaOverload.cpp:1029
clang::Module
Describes a module or submodule.
Definition: Module.h:96
clang::CXXMethodDecl::overridden_methods
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2427
clang::TemplateParameterList::getParam
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:138
clang::Sema::VariadicDoesNotApply
@ VariadicDoesNotApply
Definition: Sema.h:12029
clang::DeclarationName::getCXXOverloadedOperator
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Definition: DeclarationName.h:460
clang::Sema::inTemplateInstantiation
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:9479
clang::Declarator::hasGroupingParens
bool hasGroupingParens() const
Definition: DeclSpec.h:2562
clang::DeclSpec::hasTypeSpecifier
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:621
clang::OverridingMethods::iterator
MapType::iterator iterator
Definition: CXXInheritance.h:277
clang::FTIHasNonVoidParameters
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
clang::Sema::TPC_TypeAliasTemplate
@ TPC_TypeAliasTemplate
Definition: Sema.h:8005
clang::UsingShadowDecl::getIntroducer
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:2985
clang::ASTContext::WideCharTy
CanQualType WideCharTy
Definition: ASTContext.h:1096
clang::ASTContext::NumImplicitMoveAssignmentOperators
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3119
clang::PartialDiagnosticAt
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
Definition: PartialDiagnostic.h:205
clang::Sema::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1778
clang::Sema::UPPC_Initializer
@ UPPC_Initializer
An initializer.
Definition: Sema.h:8474
clang::CXXMethodDecl::isInstance
bool isInstance() const
Definition: DeclCXX.h:1995
clang::TemplateArgumentListInfo
A convenient class for passing around template argument information.
Definition: TemplateBase.h:563
clang::Sema::MarkAnyDeclReferenced
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19279
clang::Declarator::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1946
clang::DiagnosticsEngine::isLastDiagnosticIgnored
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:769
clang::Decl::getAccess
AccessSpecifier getAccess() const
Definition: DeclBase.h:472
clang::ASTContext::getAsConstantArrayType
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2687
clang::ThreadStorageClassSpecifier
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:220
clang::DeclAccessPair::make
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
Definition: DeclAccessPair.h:35
clang::DeclRefExpr::Create
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:452
clang::Sema::CurFPFeatureOverrides
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:874
clang::CXXRecordDecl::methods
method_range methods() const
Definition: DeclCXX.h:638
ComputeDefaultedComparisonExceptionSpec
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
Definition: SemaDeclCXX.cpp:8824
clang::FunctionDecl::isTrivial
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2207
clang::Stmt::printPretty
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
Definition: StmtPrinter.cpp:2669
clang::TagTypeKind
TagTypeKind
The kind of a tag type.
Definition: Type.h:5386
clang::diff::Move
@ Move
Definition: ASTDiff.h:32
Node
DynTypedNode Node
Definition: ASTMatchFinder.cpp:68
findImplicitlyDeclaredEqualityComparisons
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
Definition: SemaDeclCXX.cpp:10144
clang::ComparisonCategoryInfo::Record
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
Definition: ComparisonCategories.h:118
clang::CXXConstructExpr::ConstructionKind
ConstructionKind
Definition: ExprCXX.h:1464
clang::Sema::UpdateExceptionSpec
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
Definition: SemaExceptionSpec.cpp:242
clang::ASTContext::NumImplicitCopyAssignmentOperators
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3112
clang::DeclSpec::getTypeSpecType
TST getTypeSpecType() const
Definition: DeclSpec.h:476
clang::ConstexprSpecKind::Consteval
@ Consteval
clang::Sema::CXXMoveAssignment
@ CXXMoveAssignment
Definition: Sema.h:1674
clang::AtomicTypeLoc
Definition: TypeLoc.h:2531
CheckConstexprFunctionStmt
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
Definition: SemaDeclCXX.cpp:2025
clang::ExceptionSpecificationType
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
Definition: ExceptionSpecificationType.h:20
clang::Sema::CheckPureMethod
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
Definition: SemaDeclCXX.cpp:17573
clang::Sema::ActOnFinishDelayedMemberInitializers
void ActOnFinishDelayedMemberInitializers(Decl *Record)
Definition: SemaDeclCXX.cpp:13514
clang::ASTContext::getDefaultCallingConvention
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
Definition: ASTContext.cpp:11628
clang::Sema::AddImplicitlyDeclaredMembersToClass
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
Definition: SemaDeclCXX.cpp:10185
clang::Sema::ActOnFinishNamespaceDef
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
Definition: SemaDeclCXX.cpp:11266
clang::Decl::ModuleOwnershipKind::VisibleWhenImported
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3861
clang::Decl::setAccess
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:467
clang::TemplateTypeParmType::getIndex
unsigned getIndex() const
Definition: Type.h:4877
clang::FunctionDecl::getTemplatedKind
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3689
TSK_CompleteObject
@ TSK_CompleteObject
The object is actually the complete object.
Definition: SemaDeclCXX.cpp:9651
clang::VarDecl::isStaticLocal
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1124
clang::FunctionProtoType::ExceptionSpecInfo
Holds information about the various types of exception specification.
Definition: Type.h:3957
clang::TST_decltype
@ TST_decltype
Definition: Specifiers.h:84
clang::Sema::CheckTemplateDeclScope
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
Definition: SemaTemplate.cpp:7926
clang::TemplateArgumentListInfo::addArgument
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:603
clang::Sema::CheckVirtualSYCLAddIRAttributesFunctionAttr
void CheckVirtualSYCLAddIRAttributesFunctionAttr(const NamedDecl *D)
CheckVirtualSYCLAddIRAttributesFunctionAttr - Check and diagnose if a SYCLAddIRAttributesFunctionAttr...
Definition: SemaDeclCXX.cpp:3129
clang::DeclContext::getDeclKind
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1865
clang::LambdaExpr
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1865
clang::Sema::MergeCXXFunctionDecl
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Definition: SemaDeclCXX.cpp:448
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
clang::Decl::FOK_None
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1142
clang::Sema::EnterDeclaratorContext
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1340
isVirtualDirectBase
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
Definition: SemaDeclCXX.cpp:12055
clang::TemplateIdAnnotation::RAngleLoc
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
Definition: ParsedTemplate.h:182
clang::Sema::DefaultedFunctionKind::isComparison
bool isComparison() const
Definition: Sema.h:3464
clang::UnaryOperator::isIncrementDecrementOp
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2317
clang::FunctionProtoType::hasExtParameterInfos
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:4294
clang::interp::LE
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:239
clang::CXXScopeSpec::isValid
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:197
clang::syntax::NodeRole::Callee
@ Callee
clang::DeclarationName::CXXDestructorName
@ CXXDestructorName
Definition: DeclarationName.h:205
clang::Decl::setModuleOwnershipKind
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:814
clang::ASTContext::getAsArrayType
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Definition: ASTContext.cpp:6678
clang::Sema::StdInitializerList
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:1308
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:220
clang::ParmVarDecl::setDefaultArg
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2835
clang::Sema::RequireNonAbstractType
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Definition: SemaDeclCXX.cpp:5793
clang::Sema::VariadicCallType
VariadicCallType
Definition: Sema.h:12024
clang::AS_public
@ AS_public
Definition: Specifiers.h:109
clang::Sema::CheckComparisonCategoryType
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
Definition: SemaDeclCXX.cpp:11339
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:89
clang::DeclSpec::getUnalignedSpecLoc
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:552
clang::DeclAccessPair
A POD class for pairing a NamedDecl* with an access specifier.
Definition: DeclAccessPair.h:29
clang::VectorType
Represents a GCC generic vector type.
Definition: Type.h:3244
clang::ComparisonCategories::getPossibleResultsForType
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
Definition: ComparisonCategories.cpp:202
clang::FunctionDecl::getReturnTypeSourceRange
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3569
clang::Sema::VariadicConstructor
@ VariadicConstructor
Definition: Sema.h:12028
clang::ParamIdx
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:230
clang::InitListExpr::children
child_range children()
Definition: Expr.h:5031
clang::ASTContext::DependentTy
CanQualType DependentTy
Definition: ASTContext.h:1120
clang::Sema::PushDeclContext
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1305
clang::VarDecl::isStaticDataMember
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1199
clang::TagDecl::getInnerLocStart
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3418
clang::Declarator::isFunctionDeclarationContext
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2352
clang::FPOptionsOverride
Represents difference between two FPOptions values.
Definition: LangOptions.h:654
clang::FunctionDecl::getExceptionSpecType
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2565
clang::CXXCtorInitializer::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2553
clang::Sema::InheritedConstructorInfo::InheritedConstructorInfo
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
Definition: SemaDeclCXX.cpp:7116
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:208
clang::ASTContext::getSizeType
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Definition: ASTContext.cpp:5827
clang::MultiTemplateParamsArg
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:276
clang::Sema::AbstractArrayType
@ AbstractArrayType
Definition: Sema.h:7807
clang::ExprResult
ActionResult< Expr * > ExprResult
Definition: Ownership.h:262
clang::Sema::CheckConstexprKind::Diagnose
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
clang::CXXRecordDecl::implicitCopyConstructorHasConstParam
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:808
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:48
clang::Sema::warnOnReservedIdentifier
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:5786
clang::ArrayType
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2898
CXXFieldCollector.h
clang::DeclarationNameTable::getCXXOperatorName
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
Definition: DeclarationName.h:637
clang::Decl::FOK_Undeclared
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1144
clang::Sema::ActOnExprStmt
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition: SemaStmt.cpp:46
clang::Sema::ActOnBaseSpecifiers
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
Definition: SemaDeclCXX.cpp:2824
clang::Sema::BuildQualifiedType
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1901
clang::DeclaratorContext::Member
@ Member
clang::DeclarationName::getAsString
std::string getAsString() const
Retrieve the human-readable string for this name.
Definition: DeclarationName.cpp:235
clang::ParsedAttributesView::const_iterator
Definition: ParsedAttr.h:941
Std
LangStandard::Kind Std
Definition: InterpolatingCompilationDatabase.cpp:134
clang::RecursiveASTVisitor
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Definition: RecursiveASTVisitor.h:164
clang::CXXRecordDecl::getLambdaStaticInvoker
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition: DeclCXX.cpp:1523
clang::LazyVector::end
iterator end()
Definition: ExternalASTSource.h:545
clang::Qualifiers::addAddressSpace
void addAddressSpace(LangAS space, bool AllowDefaultAddrSpace=false)
Definition: Type.h:389
findDirectBaseWithType
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
Definition: SemaDeclCXX.cpp:12157
clang::Qualifiers::removeConst
void removeConst()
Definition: Type.h:266
clang::DeclaratorChunk::Pointer
@ Pointer
Definition: DeclSpec.h:1177
clang::NestedNameSpecifierLoc::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Definition: NestedNameSpecifier.cpp:410
checkSimpleDecomposition
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
Definition: SemaDeclCXX.cpp:905
clang::DependentNameTypeLoc
Definition: TypeLoc.h:2319
clang::DeclaratorChunk::FunctionTypeInfo::isVariadic
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition: DeclSpec.h:1285
clang::DecompositionDecl
A decomposition declaration.
Definition: DeclCXX.h:4036
clang::FunctionDecl::getBody
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3052
clang::DeclaratorChunk::FunctionTypeInfo
Definition: DeclSpec.h:1276
clang::CXXBaseSpecifier::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:190
Depth
int Depth
Definition: ASTDiff.cpp:191
clang::Declarator::getDecompositionDeclarator
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:1931
clang::CXXRecordDecl::needsImplicitCopyConstructor
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:787
clang::DeclSpec::hasConstexprSpecifier
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:759
clang::Sema::CXXCopyConstructor
@ CXXCopyConstructor
Definition: Sema.h:1671
clang::DeclSpec::ClearStorageClassSpecs
void ClearStorageClassSpecs()
Definition: DeclSpec.h:454
clang::CXXRecordDecl::setImplicitMoveAssignmentIsDeleted
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:954
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7263
clang::DeclContext::makeDeclVisibleInContext
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1847
clang::CXXBaseSpecifier::getAccessSpecifier
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:226
clang::FunctionProtoType::ExceptionSpecInfo::Exceptions
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3962
clang::Sema::FindHiddenVirtualMethods
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
Definition: SemaDeclCXX.cpp:9987
clang::LookupResult::makeFilter
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:682
clang::ASTContext::getRValueReferenceType
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
Definition: ASTContext.cpp:3430
clang::CXXRecordDecl::getNumBases
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:590
clang::Decl::isInvalidDecl
bool isInvalidDecl() const
Definition: DeclBase.h:552
checkArrayLikeDecomposition
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
Definition: SemaDeclCXX.cpp:932
clang::Sema::ExpressionEvaluationContext::Unevaluated
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
clang::CallExpr::getArg
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3044
CheckPolymorphic
#define CheckPolymorphic(Type)
Definition: SemaDeclCXX.cpp:5921
clang::TemplateArgument
Represents a template argument.
Definition: TemplateBase.h:61
clang::OCD_AmbiguousCandidates
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:74
clang::ASTMutationListener
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Definition: ASTMutationListener.h:46
clang::Sema::DiagnoseUnexpandedParameterPack
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
Definition: SemaTemplateVariadic.cpp:380
clang::EST_DynamicNone
@ EST_DynamicNone
throw()
Definition: ExceptionSpecificationType.h:22
clang::DeclarationName::CXXOperatorName
@ CXXOperatorName
Definition: DeclarationName.h:207
clang::FunctionType::getCallConv
CallingConv getCallConv() const
Definition: Type.h:3835
clang::VirtSpecifiers::isFinalSpelledSealed
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2638
clang::CXXRecordDecl::isAggregate
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1105
clang::DeclarationNameInfo::setName
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
Definition: DeclarationName.h:782
clang::Sema::DefaultedComparisonKind::None
@ None
This is not a defaultable comparison operator.
clang::commonComparisonType
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
Definition: ComparisonCategories.h:54
clang::Sema::AddInitializerToDecl
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:12371
clang::Sema::PerformContextuallyConvertToBool
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
Definition: SemaOverload.cpp:5608
clang::Expr::containsErrors
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:238
clang::Sema::CheckSpecifiedExceptionType
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
Definition: SemaExceptionSpec.cpp:120
clang::ASTContext::NumImplicitDefaultConstructorsDeclared
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3095
clang::Sema::Ovl_Match
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:3765
clang::DeclSpec::SCS_typedef
@ SCS_typedef
Definition: DeclSpec.h:235
clang::IdentifierInfo::getLength
unsigned getLength() const
Efficiently return the length of this identifier info.
Definition: IdentifierTable.h:192
clang::Sema::Diags
DiagnosticsEngine & Diags
Definition: Sema.h:589
clang::Attr::getKind
attr::Kind getKind() const
Definition: Attr.h:84
clang::FunctionProtoType::getParamType
QualType getParamType(unsigned i) const
Definition: Type.h:4112
clang::ParmVarDecl::hasUnparsedDefaultArg
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1781
clang::UnqualifiedIdKind::IK_LiteralOperatorId
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
clang::CXXRecordDecl::ctors
ctor_range ctors() const
Definition: DeclCXX.h:658
clang::InitializedEntity::InitializeBinding
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
Definition: Initialization.h:405
clang::Qualifiers::Volatile
@ Volatile
Definition: Type.h:152
clang::CallExpr::isCallToStdMove
bool isCallToStdMove() const
Definition: Expr.h:3183
clang::Sema::CheckCompleteDestructorVariant
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
Definition: SemaDeclCXX.cpp:13803
clang::PseudoObjectExpr
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6153
clang::FunctionDecl::setWillHaveBody
void setWillHaveBody(bool V=true)
Definition: Decl.h:2432
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:909
clang::CXXRecordDecl::needsOverloadResolutionForMoveConstructor
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition: DeclCXX.h:883
clang::UsingDecl::getUsingLoc
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3426
clang::Sema::ProcessAccessDeclAttributeList
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
clang::ComparisonCategoryType
ComparisonCategoryType
An enumeration representing the different comparison categories types.
Definition: ComparisonCategories.h:44
clang::LazyVector::push_back
void push_back(const T &LocalValue)
Definition: ExternalASTSource.h:549
clang::isExternallyVisible
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:91
clang::Stmt::children
child_range children()
Definition: Stmt.cpp:285
clang::IntegerLiteral::Create
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:953
clang::Sema::CheckExplicitlyDefaultedSpecialMember
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM)
Definition: SemaDeclCXX.cpp:7423
clang::Type::isLValueReferenceType
bool isLValueReferenceType() const
Definition: Type.h:6766
clang::Sema::DiagnoseNontrivial
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
Definition: SemaDeclCXX.cpp:9758
clang::index::SymbolKind::Field
@ Field
clang::ComparisonCategories::lookupInfoForType
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
Definition: ComparisonCategories.cpp:125
clang::BinaryConditionalOperator
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4261
clang::Sema::PDiag
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
clang::ASTContext::getTypeSize
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2282
clang::TypedefNameDecl::getUnderlyingType
QualType getUnderlyingType() const
Definition: Decl.h:3239
clang::Stmt::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:348
clang::ASTContext::getAutoDeductType
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
Definition: ASTContext.cpp:5797
clang::CXXRecordDecl::hasIrrelevantDestructor
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1357
clang::CXXDestructorDecl
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2688
clang::ImplicitCastExpr::Create
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2028
clang::Sema::GetTypeFromParser
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3020
clang::DeclContext::isTranslationUnit
bool isTranslationUnit() const
Definition: DeclBase.h:1947
clang::CXXBaseSpecifier::isVirtual
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:199
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1295
clang::Type::isFunctionType
bool isFunctionType() const
Definition: Type.h:6746
clang::Sema::SubstAutoType
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
Definition: SemaTemplateDeduction.cpp:4804
clang::UnresolvedLookupExpr::Create
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:369
clang::InitializedEntity::InitializeBase
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
Definition: SemaInit.cpp:3290
clang::TemplateArgumentLoc
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:457
clang::FunctionProtoType::ExtProtoInfo::ExtInfo
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3984
clang::Declarator::setInvalidType
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2556
clang::ParsedAttr
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:240
IndirectBaseSet
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
Definition: SemaDeclCXX.cpp:2691
clang::DeclContext::isStdNamespace
bool isStdNamespace() const
Definition: DeclBase.cpp:1135
clang::UsingDecl::Create
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3045
clang::Type::isSizelessType
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2322
clang::FunctionType::ExtParameterInfo::isNoEscape
bool isNoEscape() const
Definition: Type.h:3626
clang::UnqualifiedIdKind::IK_ConstructorName
@ IK_ConstructorName
A constructor name.
clang::Sema::ActOnAliasDeclaration
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
Definition: SemaDeclCXX.cpp:12948
clang::CPlusPlus20
@ CPlusPlus20
Definition: LangStandard.h:52
clang::FieldDecl::hasInClassInitializer
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:2979
clang::Sema::ShouldDeleteSpecialMember
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
Definition: SemaDeclCXX.cpp:9342
clang::Sema::CodeSynthesisContext
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9048
clang::Sema::Ovl_Overload
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:3761
clang::FriendDecl::Create
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=None)
Definition: DeclFriend.cpp:34
llvm::SmallString< 128 >
clang::ImplicitValueInitExpr
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5563
clang::FriendDecl
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:53
clang::ASTContext::adjustExceptionSpec
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
Definition: ASTContext.cpp:3212
clang::Sema::ProcessDeclAttributeList
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes=true)
clang::Redeclarable::redecls
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
clang::ParmVarDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2793
clang::BaseUsingDecl::removeShadowDecl
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3023
clang::ICIS_ListInit
@ ICIS_ListInit
Direct list-initialization.
Definition: Specifiers.h:259
clang::Sema::getDefaultedFunctionKind
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
Definition: SemaDeclCXX.cpp:6527
clang::FunctionDecl::DefaultedFunctionInfo::Create
static DefaultedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups)
Definition: Decl.cpp:2947
clang::TypeAliasDecl::setDescribedAliasTemplate
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3324
clang::Sema::GetNameForDeclarator
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5534
ASTContext.h
clang::ASTContext::getRecordType
QualType getRecordType(const RecordDecl *Decl) const
Definition: ASTContext.cpp:4641
clang::ASTContext::CompCategories
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2224
clang::interp::Zero
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:814
clang::UnresolvedSet
A set of unresolved declarations.
Definition: UnresolvedSet.h:148
clang::CallingConv
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:263
clang::Sema::ActOnUsingEnumDeclaration
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, const DeclSpec &)
Definition: SemaDeclCXX.cpp:11824
clang::ParmVarDecl::setUninstantiatedDefaultArg
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2860
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:875
clang::TemplateArgumentLoc::getArgument
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:506
DelegatingCycleHelper
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
Definition: SemaDeclCXX.cpp:17945
clang::FunctionProtoType::getParamTypes
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4117
clang::Sema::DeduceReturnType
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
Definition: SemaTemplateDeduction.cpp:4858
Category
int Category
Definition: Format.cpp:2553
clang::TemplateName::Template
@ Template
A single template declaration.
Definition: TemplateName.h:203
clang::DeclSpec::isFriendSpecified
bool isFriendSpecified() const
Definition: DeclSpec.h:748
clang::TagDecl
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3332
clang::Type::getPointeeType
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:625
clang::CXXBaseSpecifier::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:189
clang::ConstexprSpecKind::Constexpr
@ Constexpr
clang::Sema::ActOnStaticAssertDeclaration
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
Definition: SemaDeclCXX.cpp:16547
clang::Type::getCanonicalTypeInternal
QualType getCanonicalTypeInternal() const
Definition: Type.h:2466
clang::Sema::LookupDestructor
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
Definition: SemaLookup.cpp:3436
clang::TemplateParameterList
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:69
clang::TSK_ExplicitInstantiationDefinition
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:191
clang::CXXRecordDecl::hasConstexprDestructor
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:561
clang::StringLiteral
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1767
CheckOperatorNewDeleteTypes
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
Definition: SemaDeclCXX.cpp:15744
clang::SourceRange::setEnd
void setEnd(SourceLocation e)
Definition: SourceLocation.h:223
clang::DeclSpec::getStorageClassSpec
SCS getStorageClassSpec() const
Definition: DeclSpec.h:440
isInvalid
static bool isInvalid(LocType Loc, bool *Invalid)
Definition: SourceManager.cpp:1227
clang::OverloadCandidateSet::iterator
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1103
clang::TTK_Class
@ TTK_Class
The "class" keyword.
Definition: Type.h:5397
clang::CXXConstructExpr::getConstructor
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1532
clang::Sema::SpecialMemberOverloadResult::getMethod
CXXMethodDecl * getMethod() const
Definition: Sema.h:1562
clang::NUM_OVERLOADED_OPERATORS
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
clang::ASTContext::getCanonicalType
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2505
clang::CXXRecordDecl::isDerivedFrom
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Definition: CXXInheritance.cpp:68
clang::TypeDecl
Represents a declaration of a type.
Definition: Decl.h:3142
clang::DeclaratorDecl::getTrailingRequiresClause
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:803
clang::NestedNameSpecifier::Global
@ Global
The global specifier '::'. There is no stored value.
Definition: NestedNameSpecifier.h:97
clang::Type::getAsCXXRecordDecl
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1760
clang::Sema::AA_Passing
@ AA_Passing
Definition: Sema.h:3748
clang::Sema::CheckRedeclarationInModule
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1689
NoteIndirectBases
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
Definition: SemaDeclCXX.cpp:2695
clang::TagDecl::isUnion
bool isUnion() const
Definition: Decl.h:3538
clang::RQ_None
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1445
clang::LinkageSpecDecl::LanguageIDs
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2826
clang::Sema::LookupParsedName
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Definition: SemaLookup.cpp:2520
clang::CXXRecordDecl::hasDirectFields
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition: DeclCXX.h:1162
clang::EmptyDecl::Create
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5114
clang::Type::isVariablyModifiedType
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2201
clang::OR_Deleted
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:62
clang::CXXRecordDecl::bases
base_class_range bases()
Definition: DeclCXX.h:596
clang::Sema::getLocForEndOfToken
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:54
clang::CXXThisExpr::getBeginLoc
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:1156
clang::Type::isUndeducedAutoType
bool isUndeducedAutoType() const
Definition: Type.h:6895
clang::CXXRecordDecl::implicitCopyAssignmentHasConstParam
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition: DeclCXX.h:927
clang::FunctionDecl::setPure
void setPure(bool P=true)
Definition: Decl.cpp:3071
clang::Sema::getCurFPFeatures
FPOptions & getCurFPFeatures()
Definition: Sema.h:1776
clang::EnumConstantDecl
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3054
clang::FunctionType::ExtInfo::withCallingConv
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:3787
clang::DeclSpec::SetStorageClassSpec
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:618
clang::IfStmt::getElse
Stmt * getElse()
Definition: Stmt.h:2009
clang::Sema::FindDeallocationFunctionForDestructor
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
Definition: SemaExprCXX.cpp:3165
clang::CXXTryStmt
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:68
clang::Sema::CheckInheritingConstructorUsingDecl
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
Definition: SemaDeclCXX.cpp:12607
clang::NestedNameSpecifierLoc
A C++ nested-name-specifier augmented with source location information.
Definition: NestedNameSpecifier.h:243
clang::TypeLoc::isNull
bool isNull() const
Definition: TypeLoc.h:120
clang::Redeclarable::getPreviousDecl
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
clang::FunctionDecl::getMinRequiredArguments
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3423
clang::FunctionDecl::setParams
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2518
clang::Sema::PureVirtualClassDiagSet
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:1024
clang::CanQual< Type >
ExprCXX.h
clang::Sema::ActOnStartDelayedMemberDeclarations
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
Definition: SemaDeclCXX.cpp:10349
clang::LookupResult::Filter::erase
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:654
Base
clang::Sema::checkExceptionSpecification
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
Definition: SemaDeclCXX.cpp:18164
clang::DeclaratorChunk::BlockPointer
@ BlockPointer
Definition: DeclSpec.h:1177
clang::FunctionDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3937
clang::DeclContext::isRecord
bool isRecord() const
Definition: DeclBase.h:1951
clang::FunctionDecl::getOverloadedOperator
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3675
clang::MemberPointerTypeLoc
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1288
clang::UnresolvedUsingValueDecl
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3733
clang::CXXInheritedCtorInitExpr
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1651
clang::Sema::getDefaultCXXMethodAddrSpace
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1512
clang::TagDecl::isCompleteDefinition
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3437
clang::ComparisonCategories::lookupInfo
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified 'Kind'.
Definition: ComparisonCategories.cpp:112
clang::interp::Const
bool Const(InterpState &S, CodePtr OpPC, const T &Arg)
Definition: Interp.h:296
clang::LangOptions::ClangABI::Ver4
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
clang::Sema::BuildUsingShadowDecl
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
Definition: SemaDeclCXX.cpp:12065
clang::Sema::DefaultedComparisonKind::ThreeWay
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
clang::Type::isEnumeralType
bool isEnumeralType() const
Definition: Type.h:6844
clang::DeclaratorChunk::FunctionTypeInfo::Params
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1340
clang::Sema::TAH_ConsiderTrivialABI
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:3442
clang::Sema::DefaultedComparisonKind::NotEqual
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
clang::Decl::setImplicit
void setImplicit(bool I=true)
Definition: DeclBase.h:558
clang::DeclaratorChunk::FunctionTypeInfo::freeParams
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1379
clang::Sema::isVisible
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:2535
clang::QualType::hasQualifiers
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6577
clang::Sema::ResolveExceptionSpec
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
Definition: SemaExceptionSpec.cpp:209
clang::LookupResult::Ambiguous
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
clang::DeclSpec::ClearConstexprSpec
void ClearConstexprSpec()
Definition: DeclSpec.h:763
clang::Sema::DiagnoseFunctionSpecifiers
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6334
clang::NestedNameSpecifierLocBuilder
Class that aids in the construction of nested-name-specifiers along with source-location information ...
Definition: NestedNameSpecifier.h:356
clang::Sema::CheckCXXDefaultArgExpr
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5867
clang::DeclSpec::getThreadStorageClassSpecLoc
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:450
clang::Sema::diagnoseIgnoredQualifiers
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:3140
clang::Sema::getASTMutationListener
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:575
clang::TemplateTypeParmDecl
Declaration of a template type parameter.
Definition: DeclTemplate.h:1179
clang::DeclSpec::SCS_mutable
@ SCS_mutable
Definition: DeclSpec.h:241
clang::ConstructorUsingShadowDecl::Create
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:2996
clang::Sema::DiagnoseUnexpandedParameterPacks
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
Definition: SemaTemplateVariadic.cpp:290
clang::Sema::LookupName
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
Definition: SemaLookup.cpp:1985
clang::Sema::CodeSynthesisContext::SpecialMember
CXXSpecialMember SpecialMember
The special member being declared or defined.
Definition: Sema.h:9170
clang::Sema::actOnDelayedExceptionSpecification
void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member function (or member function template).
Definition: SemaDeclCXX.cpp:18213
clang::Declarator::isFunctionDeclarator
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2298
clang::RecordDecl::isAnonymousStructOrUnion
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:3958
clang::VarDecl::Create
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2051
clang::DeclaratorChunk::FunctionTypeInfo::hasRefQualifier
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1466
clang::TemplateParameterList::getTemplateLoc
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:193
clang::CXXScopeSpec::getWithLocInContext
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:151
clang::CXXRecordDecl::vbases
base_class_range vbases()
Definition: DeclCXX.h:613
clang::CastExpr::getCastKind
CastKind getCastKind() const
Definition: Expr.h:3576
clang::Decl::isImplicit
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:557
clang::OverloadedOperatorKind
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
clang::IfStatementKind::Ordinary
@ Ordinary
clang::DeclaratorChunk::ParamInfo::Param
Decl * Param
Definition: DeclSpec.h:1254
clang::MemberExpr::getMemberDecl
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3303
getTrivialIntegralTemplateArgument
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
Definition: SemaDeclCXX.cpp:1055
clang::NamespaceDecl::setRBraceLoc
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:659
clang::TypeAliasDecl::Create
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5069
clang::ASTContext::Deallocate
void Deallocate(void *Ptr) const
Definition: ASTContext.h:731
clang::Sema::ConditionResult
Definition: Sema.h:12527
clang::Sema::PopExpressionEvaluationContext
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17300
clang::Decl::dropAttr
void dropAttr()
Definition: DeclBase.h:512
clang::DecompositionDeclarator::getSourceRange
SourceRange getSourceRange() const
Definition: DeclSpec.h:1747
clang::CXXDestructorDecl::Create
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2738
clang::Sema::SynthesizedFunctionScope
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:1213
clang::Sema::BuildStaticAssertDeclaration
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
Definition: SemaDeclCXX.cpp:16561
clang::StringLiteral::isAscii
bool isAscii() const
Definition: Expr.h:1886
clang::DeclRefExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:515
CheckOperatorNewDeclaration
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
Definition: SemaDeclCXX.cpp:15815
clang::Decl::IDNS_Ordinary
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:141
clang::SC_Static
@ SC_Static
Definition: Specifiers.h:237
getImplicitMethodEPI
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
Definition: SemaDeclCXX.cpp:7376
clang::ASTConsumer::HandleTopLevelDecl
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
clang::Declarator::SetIdentifier
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2197
clang::Sema::LangOpts
const LangOptions & LangOpts
Definition: Sema.h:585
clang::Sema::DefineImplicitMoveConstructor
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
Definition: SemaDeclCXX.cpp:15266
clang::CXXRecordDecl::hasUserDeclaredCopyAssignment
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition: DeclCXX.h:891
clang::TemplateDecl::getTemplateParameters
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:419
clang::Sema::DefaultedFunctionKind::isSpecialMember
bool isSpecialMember() const
Definition: Sema.h:3463
clang::ASTContext::UnsignedLongLongTy
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1103
clang::ETK_None
@ ETK_None
No keyword precedes the qualified type name.
Definition: Type.h:5426
clang::QualType::getUnqualifiedType
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6582
clang::UsingDecl
Represents a C++ using-declaration.
Definition: DeclCXX.h:3399
clang::CXXBasePaths::paths_iterator
std::list< CXXBasePath >::iterator paths_iterator
Definition: CXXInheritance.h:171
CharUnits.h
clang::Sema::CheckUsingDeclRedeclaration
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
Definition: SemaDeclCXX.cpp:12637
clang::Sema::PerformImplicitConversion
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit=false)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType.
Definition: SemaOverload.cpp:1495
clang::DeclarationNameInfo::getName
DeclarationName getName() const
getName - Returns the embedded declaration name.
Definition: DeclarationName.h:779
clang::Sema::ImplicitExceptionSpecification::CalledStmt
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
Definition: SemaDeclCXX.cpp:229
canPassInRegisters
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
Definition: SemaDeclCXX.cpp:6613
clang::CXXRecordDecl::hasInheritedAssignment
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition: DeclCXX.h:1375
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:6878
clang::LookupResult::Filter::hasNext
bool hasNext() const
Definition: Lookup.h:639
clang::Sema::tryResolveExplicitSpecifier
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Definition: SemaDeclCXX.cpp:13256
ReferenceDllExportedMembers
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
Definition: SemaDeclCXX.cpp:6036
clang::FunctionDecl::hasBody
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2972
clang::Sema::CorrectTypo
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
Definition: SemaLookup.cpp:5101
clang::TemplateParameterList::getRAngleLoc
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:195
clang::Type::isFunctionProtoType
bool isFunctionProtoType() const
Definition: Type.h:2021
clang::InitializationKind::CreateDefault
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
Definition: Initialization.h:682
clang::CXXRecordDecl::hasTrivialCopyConstructorForCall
bool hasTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1237
clang::VarDecl::isNoDestroy
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2704
clang::ParmVarDecl::setHasInheritedDefaultArg
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1801
clang::Sema::CheckDeductionGuideDeclarator
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
Definition: SemaDeclCXX.cpp:10970
clang::VarDecl::getDescribedVarTemplate
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2678
clang::Sema::CheckExplicitlyDefaultedFunction
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
Definition: SemaDeclCXX.cpp:7404
clang::CXXConstructorDecl::isDefaultConstructor
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2634
clang::Sema::CheckClassTemplate
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaTemplate.cpp:1712
clang::Sema::HandleFunctionTypeMismatch
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
Definition: SemaOverload.cpp:2876
clang::Expr::isPotentialConstantExpr
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
Definition: ExprConstant.cpp:15836
clang::OpaquePtr< QualType >
clang::TemplateTypeParmType
Definition: Type.h:4835
clang::ASTContext::getExceptionObjectType
QualType getExceptionObjectType(QualType T) const
Definition: ASTContext.cpp:6748
clang::Sema::UnusedPrivateFields
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:1004
clang::ClassTemplateSpecializationDecl::isExplicitSpecialization
bool isExplicitSpecialization() const
Definition: DeclTemplate.h:1905
clang::DeclarationName::CXXConversionFunctionName
@ CXXConversionFunctionName
Definition: DeclarationName.h:206
clang::Sema::InstantiateInClassInitializer
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
Definition: SemaTemplateInstantiate.cpp:3033
clang::ExplicitSpecifier::getExpr
const Expr * getExpr() const
Definition: DeclCXX.h:1824
clang::TemplateIdAnnotation::LAngleLoc
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
Definition: ParsedTemplate.h:178
printTemplateArgs
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
Definition: SemaDeclCXX.cpp:977
clang::LangAS
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
clang::OverloadCandidateSet
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:935
clang::ComparisonCategoryInfo
Definition: ComparisonCategories.h:75
clang::CXXConstructorDecl::getCanonicalDecl
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2666
clang::DeclSpec::getStorageClassSpecLoc
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:449
clang::Sema::AbstractReturnType
@ AbstractReturnType
Definition: Sema.h:7801
clang::FunctionDecl::isDestroyingOperatorDelete
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3221
TrivialSubobjectKind
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
Definition: SemaDeclCXX.cpp:9645
clang::ASTContext::BuiltinFnTy
CanQualType BuiltinFnTy
Definition: ASTContext.h:1121
clang::VK_LValue
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:124
clang::Sema::HandleField
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:17044
clang::OCD_AllCandidates
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:68
clang::Sema::diagnoseTypo
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Definition: SemaLookup.cpp:5398
clang::FieldDecl::getFieldIndex
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4261
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7330
clang::ParmVarDecl::getUninstantiatedDefaultArg
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2865
clang::Sema::DefineImplicitMoveAssignment
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
Definition: SemaDeclCXX.cpp:14823
checkComplexDecomposition
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
Definition: SemaDeclCXX.cpp:964
clang::UnresolvedSetImpl::pairs
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:89
clang::TemplateName::getKind
NameKind getKind() const
Definition: TemplateName.cpp:82
clang::QualType::getLocalCVRQualifiers
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:802
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1160
clang::AccessSpecifier
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:108
clang::Sema::CheckOverridingFunctionAttributes
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
Definition: SemaDeclCXX.cpp:17414
clang::Sema::FinalizeVarWithDestructor
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
Definition: SemaDeclCXX.cpp:15613
clang::ParmVarDecl::hasDefaultArg
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:2871
clang::DependentNameTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
clang::UsingEnumDecl
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3599
clang::Sema::HideUsingShadowDecl
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
Definition: SemaDeclCXX.cpp:12135
clang::MemberExpr::getBase
Expr * getBase() const
Definition: Expr.h:3297
clang::InitializationSequence::Perform
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7988
clang::TemplateArgumentListInfo::arguments
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:591
clang::DecompositionDeclarator::getLSquareLoc
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1745
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
clang::CXXMethodDecl::getMethodQualifiers
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2113
clang::Sema::MarkVTableUsed
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
Definition: SemaDeclCXX.cpp:17695
clang::CXXMethodDecl::begin_overridden_methods
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2411
clang::CXXRecordDecl::needsImplicitMoveConstructor
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:873
clang::Sema::BuildMemInitializer
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
Definition: SemaDeclCXX.cpp:4225
clang::BinaryOperator::Create
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4540
clang::UnqualifiedIdKind::IK_TemplateId
@ IK_TemplateId
A template-id, e.g., f<int>.
clang::VarDecl::isThisDeclarationADefinition
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2161
clang::Sema::SetParamDefaultArgument
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
Definition: SemaDeclCXX.cpp:286
clang::MemberExpr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3415
clang::OO_None
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
clang::TypeLoc::getLocalSourceRange
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:158
clang::Sema::StdAlignValT
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:1300
clang::Declarator::getTemplateParameterLists
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2489
clang::Sema::CheckCXXDefaultArguments
void CheckCXXDefaultArguments(FunctionDecl *FD)
CheckCXXDefaultArguments - Verify that the default arguments for a function declaration are well-form...
Definition: SemaDeclCXX.cpp:1584
clang::Type::isUnionType
bool isUnionType() const
Definition: Type.cpp:595
clang::Sema::computeDeclContext
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Definition: SemaCXXScopeSpec.cpp:53
clang::DeclContext::getRedeclContext
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1792
clang::Sema::DefaultedComparisonKind
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:1688
clang::Sema::CheckImplicitSpecialMemberDeclaration
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
Definition: SemaDeclCXX.cpp:13368
clang::Sema::ActOnReenterTemplateScope
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
Definition: SemaDeclCXX.cpp:10283
clang::Sema::ActOnRequiresClause
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
Definition: SemaDeclCXX.cpp:4032
clang::Declarator::getCXXScopeSpec
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1925
clang::EST_Uninstantiated
@ EST_Uninstantiated
not instantiated yet
Definition: ExceptionSpecificationType.h:31
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::Sema::CTK_ErrorRecovery
@ CTK_ErrorRecovery
Definition: Sema.h:4544
clang::Attr::isInherited
bool isInherited() const
Definition: Attr.h:93
clang::DeclaratorChunk::FunctionTypeInfo::MethodQualifiers
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1343
clang::Type::isDependentType
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2183
clang::Sema::CheckIfOverriddenFunctionIsMarkedFinal
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
Definition: SemaDeclCXX.cpp:3183
clang::VK_PRValue
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:120
clang::TemplateSpecializationKind
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:173
clang::Sema::ActOnVariableDeclarator
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=None)
Definition: SemaDecl.cpp:7081
clang::Sema::DefineImplicitDefaultConstructor
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
Definition: SemaDeclCXX.cpp:13473
clang::Sema::DefaultedFunctionKind
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:3450
clang::Attr::clone
Attr * clone(ASTContext &C) const
clang::CXXRecordDecl::needsOverloadResolutionForCopyConstructor
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition: DeclCXX.h:793
clang::QualType::isTriviallyCopyableType
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2469
clang::Sema::DefineImplicitCopyAssignment
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
Definition: SemaDeclCXX.cpp:14459
clang::TypeWithKeyword::getTagTypeKindForTypeSpec
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2833
clang::Sema::IsDerivedFrom
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
Definition: SemaDeclCXX.cpp:2835
clang::LookupResult::suppressDiagnostics
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:583
clang::Decl::getPreviousDecl
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:992
clang::Decl::getFriendObjectKind
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1151
clang::ASTContext::VoidPtrTy
CanQualType VoidPtrTy
Definition: ASTContext.h:1119
clang::Sema::ImpCastExprToType
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:659
clang::LookupResult::empty
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
clang::Sema::CreateBuiltinUnaryOp
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:15251
clang::Sema::FullExprArg::get
Expr * get() const
Definition: Sema.h:4971
clang::Sema::PushExpressionEvaluationContext
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17023
clang::Sema::ActOnFriendTypeDecl
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
Definition: SemaDeclCXX.cpp:16847
TSK_Field
@ TSK_Field
The subobject is a non-static data member.
Definition: SemaDeclCXX.cpp:9649
clang::Sema::BuildReturnStmt
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
Definition: SemaStmt.cpp:3919
clang::Type::isPointerType
bool isPointerType() const
Definition: Type.h:6750
clang::LookupResult::isVisible
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
Definition: Lookup.h:349
clang::ElaboratedTypeLoc::getNamedTypeLoc
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2298
clang::Sema::getScopeForDeclContext
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1561
clang::Declarator::getFunctionTypeInfo
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2329
clang::UsingPackDecl::Create
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3083
clang::Sema::ActOnStartTrailingRequiresClause
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
Definition: SemaDeclCXX.cpp:4014
clang::Sema::DiagnoseReturnInConstructorExceptionHandler
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
Definition: SemaDeclCXX.cpp:17407
clang::Sema::DeclareImplicitDestructor
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Definition: SemaDeclCXX.cpp:13693
DefineDefaultedFunction
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
Definition: SemaDeclCXX.cpp:6580
clang::CXXMethodDecl::size_overridden_methods
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2421
clang::Sema::ActOnFinishFullExpr
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6830
clang::syntax::NodeRole::Size
@ Size
clang::Sema::CheckOverrideControl
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
Definition: SemaDeclCXX.cpp:3059
clang::DeclaratorChunk::Function
@ Function
Definition: DeclSpec.h:1177
clang::Sema::ImplicitExceptionSpecification::CalledDecl
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
Definition: SemaDeclCXX.cpp:161
false
#define false
Definition: stdbool.h:22
clang::Language
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:19
IIK_Move
@ IIK_Move
Definition: SemaDeclCXX.cpp:4703
clang::Sema::MarkBaseAndMemberDestructorsReferenced
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
Definition: SemaDeclCXX.cpp:5623
clang::Sema::getStdBadAlloc
CXXRecordDecl * getStdBadAlloc() const
Definition: SemaDeclCXX.cpp:11278
clang::CXXRecordDecl::getNumVBases
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:611
clang::Sema::BuildDelegatingInitializer
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
Definition: SemaDeclCXX.cpp:4481
clang::ComparisonCategoryInfo::getValueInfo
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
Definition: ComparisonCategories.h:126
clang::PseudoObjectExpr::semantics
llvm::iterator_range< semantics_iterator > semantics()
Definition: Expr.h:6234
clang::OR_No_Viable_Function
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:56
clang::Sema::ActOnFinishCXXMemberDecls
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
Definition: SemaDeclCXX.cpp:13824
clang::FunctionDecl::setTrivialForCall
void setTrivialForCall(bool IT)
Definition: Decl.h:2211
UINT_MAX
#define UINT_MAX
Definition: limits.h:56
clang::TagDecl::isBeingDefined
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3457
isTupleLike
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
Definition: SemaDeclCXX.cpp:1068
clang::FunctionDecl::param_iterator
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2495
clang::Sema::IdResolver
IdentifierResolver IdResolver
Definition: Sema.h:1284
clang::Sema::isInOpenMPDeclareTargetContext
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:11111
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:169
clang::TypeSpecTypeLoc
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:513
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:268
clang::QualType::getLocalUnqualifiedType
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:914
clang::ClassTemplateDecl
Declaration of a class template.
Definition: DeclTemplate.h:2247
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:675
clang::ComplexType
Complex values, per C99 6.2.5p11.
Definition: Type.h:2602
clang::FunctionDecl::setTrivial
void setTrivial(bool IT)
Definition: Decl.h:2208
clang::AS_protected
@ AS_protected
Definition: Specifiers.h:110
clang::CXXRecordDecl::needsImplicitCopyAssignment
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:906
clang::ASTContext::IntTy
CanQualType IntTy
Definition: ASTContext.h:1101
clang::DeclSpec::isModulePrivateSpecified
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:751
clang::Sema::ActOnTemplatedFriendTag
Decl * ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
Definition: SemaDeclCXX.cpp:16713
clang::Sema::ActOnDelayedCXXMethodParameter
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
Definition: SemaDeclCXX.cpp:10389
clang::DeclaratorChunk::Kind
enum clang::DeclaratorChunk::@210 Kind
target
target
Definition: SemaSYCL.cpp:42
clang::Sema::ForExternalRedeclaration
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
Definition: Sema.h:4365
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:190
clang::CXXRecordDecl::needsOverloadResolutionForDestructor
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:994
clang::VarDecl::getStorageClass
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1084
clang::BinaryOperator::getLHS
Expr * getLHS() const
Definition: Expr.h:3910
clang::Sema::CodeSynthesisContext::DeclaringSpecialMember
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:9103
isProvablyNotDerivedFrom
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
Definition: SemaExprMember.cpp:32
clang::FunctionDecl::setImplicitlyInline
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2612
clang::CXXRecordDecl::hasTrivialDefaultConstructor
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1195
clang::RecordDecl::APK_CannotPassInRegs
@ APK_CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition: Decl.h:3905
CheckLiteralType
static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, SourceLocation Loc, QualType T, unsigned DiagID, Ts &&...DiagArgs)
Check that the given type is a literal type.
Definition: SemaDeclCXX.cpp:1631
clang::FunctionDecl::getFunctionTypeLoc
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3563
clang::DeclContext::addDecl
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1571
clang::FunctionTypeLoc::setParam
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1465
clang::ASTContext::getTagDeclType
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
Definition: ASTContext.cpp:5817
clang::CXXRecordDecl::defaultedDestructorIsDeleted
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition: DeclCXX.h:702
clang::FunctionProtoType
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3900
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:651
clang::Sema::DeclareImplicitEqualityComparison
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Definition: SemaDeclCXX.cpp:8771
clang::Sema::inferObjCARCLifetime
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:6540
clang::CharSourceRange::getTokenRange
static CharSourceRange getTokenRange(SourceRange R)
Definition: SourceLocation.h:261
clang::UnresolvedUsingIfExistsDecl::Create
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3152
clang::DeclContext::getParent
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1872
clang::DeclSpec::forEachQualifier
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition: DeclSpec.cpp:437
clang::Expr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:246
clang::Type::isIncompleteArrayType
bool isIncompleteArrayType() const
Definition: Type.h:6824
Specifier
const NestedNameSpecifier * Specifier
Definition: USRLocFinder.cpp:173
clang::Sema::CheckUsingDeclQualifier
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
Definition: SemaDeclCXX.cpp:12719
clang::ASTContext::getPrintingPolicy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:704
clang::RecordDecl::fields
field_range fields() const
Definition: Decl.h:4105
clang::CXXConversionDecl::getConversionType
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2791
clang::TypeLoc::getAs
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
clang::Sema::getCurrentClass
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
Definition: SemaDeclCXX.cpp:2406
buildSingleCopyAssign
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
Definition: SemaDeclCXX.cpp:14303
clang::ElaboratedTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2269
clang::TemplateDecl
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:400
clang::DeclarationName::isIdentifier
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Definition: DeclarationName.h:373
clang::LookupResult::Filter::done
void done()
Definition: Lookup.h:672
clang::Sema::isInOpenMPTargetExecutionDirective
bool isInOpenMPTargetExecutionDirective() const
Return true inside OpenMP target region.
Definition: SemaOpenMP.cpp:2178
clang::TemplateSpecializationTypeLoc::getNumArgs
unsigned getNumArgs() const
Definition: TypeLoc.h:1636
clang::CXXConstructorDecl::getTargetConstructor
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2625
TypeOrdering.h
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:740
clang::TypeWithKeyword::getKeywordForTagTypeKind
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:2846
llvm::ArrayRef
Definition: LLVM.h:34
clang::FunctionProtoType::getNoexceptExpr
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4193
clang::DeclSpec::TST_typename
static const TST TST_typename
Definition: DeclSpec.h:288
clang::Sema::setTagNameForLinkagePurposes
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4696
clang::frontend::FixIt
@ FixIt
Parse and apply any fixits to the source.
Definition: FrontendOptions.h:82
clang::Sema::AR_inaccessible
@ AR_inaccessible
Definition: Sema.h:7716
clang::DeclSpec::getTypeSpecTypeNameLoc
SourceLocation getTypeSpecTypeNameLoc() const
Definition: DeclSpec.h:518
extendRight
static void extendRight(SourceRange &R, SourceRange After)
Definition: SemaDeclCXX.cpp:10714
Value
Value
Definition: UninitializedValues.cpp:102
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::Sema::CXXInvalid
@ CXXInvalid
Definition: Sema.h:1676
clang::Sema::CheckTemplateParameterList
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
Definition: SemaTemplate.cpp:2669
clang::LookupResult::setBaseObjectType
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:420
clang::ComparisonCategories::getCategoryString
static StringRef getCategoryString(ComparisonCategoryType Kind)
Definition: ComparisonCategories.cpp:171
clang::Sema::PopFunctionScopeInfo
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2294
clang::FriendDecl::setUnsupportedFriend
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:177
Scope.h
clang::Sema::ConditionResult::get
std::pair< VarDecl *, Expr * > get() const
Definition: Sema.h:12549
clang::Sema::ActOnIfStmt
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:869
IIK_Copy
@ IIK_Copy
Definition: SemaDeclCXX.cpp:4702
clang::EnterExpressionEvaluationContext
RAII object that enters a new expression evaluation context.
Definition: Sema.h:13792
clang::InitializedEntity::InitializeDelegation
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
Definition: Initialization.h:371
clang::Declarator::isFunctionDefinition
bool isFunctionDefinition() const
Definition: DeclSpec.h:2576
clang::DeclaratorDecl
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:727
checkVectorDecomposition
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
Definition: SemaDeclCXX.cpp:955
clang::FunctionDecl::isPure
bool isPure() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2190
clang::TypeLoc
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
clang::Expr::IgnoreParenImpCasts
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2948
clang::Sema::checkThisInStaticMemberFunctionType
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
Definition: SemaDeclCXX.cpp:18038
clang::Sema::CheckDestructorDeclarator
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
Definition: SemaDeclCXX.cpp:10606
clang::LinkageSpecDecl::lang_cxx
@ lang_cxx
Definition: DeclCXX.h:2826
clang::Sema::ActOnExceptionDeclarator
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
Definition: SemaDeclCXX.cpp:16496
clang::DeclGroupRef
Definition: DeclGroup.h:51
clang::DeclarationNameInfo::setNamedTypeInfo
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
Definition: DeclarationName.h:805
clang::CXXRecordDecl::hasTrivialMoveConstructor
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1256
clang::frontend::After
@ After
Like System, but searched after the system directories.
Definition: HeaderSearchOptions.h:61
clang::CXXConstructorDecl::getInheritedConstructor
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2661
clang::UsingDecl::getNameInfo
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3440
clang::DeclSpec::getInlineSpecLoc
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:570
clang::Sema::ActOnDeclarator
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:5799
clang::Sema::SpecialMemberDecl
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMember > SpecialMemberDecl
Definition: Sema.h:1680
clang::Sema::Consumer
ASTConsumer & Consumer
Definition: Sema.h:588
clang::Sema::AddBuiltinOperatorCandidates
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
Definition: SemaOverload.cpp:9190
clang::Sema::DefaultLvalueConversion
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:667
clang::FunctionDecl::isTrivialForCall
bool isTrivialForCall() const
Definition: Decl.h:2210
clang::Sema::ActOnFinishDelayedCXXMethodDeclaration
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
Definition: SemaDeclCXX.cpp:10406
ASTMutationListener.h
GetKeyForBase
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
Definition: SemaDeclCXX.cpp:5333
clang::CXXRecordDecl::needsImplicitMoveAssignment
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:964
clang::DeclContext::getOuterLexicalRecordContext
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1818
clang::Sema::popCodeSynthesisContext
void popCodeSynthesisContext()
Definition: SemaTemplateInstantiate.cpp:439
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:531
clang::FunctionDecl::TK_NonTemplate
@ TK_NonTemplate
Definition: Decl.h:1865
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:165
StmtVisitor.h
clang::UnqualifiedIdKind::IK_DestructorName
@ IK_DestructorName
A destructor name.
clang::Sema::DiagnoseUseOfDecl
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:217
clang::QualType::isPODType
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2361
clang::TypeLoc::getType
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:132
clang::Sema::TypeDiagnoser::diagnose
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
clang::Sema::CheckExtraCXXDefaultArguments
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
Definition: SemaDeclCXX.cpp:393
clang::Sema::getStdAlignValT
EnumDecl * getStdAlignValT() const
Definition: SemaDeclCXX.cpp:11283
clang::TypeAliasTemplateDecl::Create
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Definition: DeclTemplate.cpp:1121
clang::Sema::DeclareImplicitCopyAssignment
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
Definition: SemaDeclCXX.cpp:14323
clang::Qualifiers::addConst
void addConst()
Definition: Type.h:267
clang::DeclContextLookupResult::end
iterator end()
Definition: DeclBase.h:1315
clang::ASTContext::CharTy
CanQualType CharTy
Definition: ASTContext.h:1094
clang::Sema::InstantiateDefaultCtorDefaultArgs
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
Definition: SemaTemplateInstantiateDecl.cpp:1233
clang::ClassTemplateDecl::getCanonicalDecl
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
Definition: DeclTemplate.h:2324
clang::ComparisonCategoryResult::Equivalent
@ Equivalent
clang::ClassTemplateDecl::getTemplatedDecl
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Definition: DeclTemplate.h:2295
diagnoseDeprecatedCopyOperation
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
Definition: SemaDeclCXX.cpp:14408
clang::TSK_ExplicitSpecialization
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:183
clang::EST_MSAny
@ EST_MSAny
Microsoft throw(...) extension.
Definition: ExceptionSpecificationType.h:24
clang::NamespaceAliasDecl::Create
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:2912
clang::LazyVector::begin
iterator begin(Source *source, bool LocalOnly=false)
Definition: ExternalASTSource.h:536
clang::Decl::attrs
attr_range attrs() const
Definition: DeclBase.h:500
clang::CXXRecordDecl::defaultedDefaultConstructorIsConstexpr
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1218
clang::Declarator::isInvalidType
bool isInvalidType() const
Definition: DeclSpec.h:2557
clang::CXXConstructorDecl::init_begin
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2520
clang::FunctionProtoType::getNumParams
unsigned getNumParams() const
Definition: Type.h:4110
clang::OR_Ambiguous
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:59
clang::Sema::DelayedDllExportClasses
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:13544
clang::ASTContext::MakeIntValue
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
Definition: ASTContext.h:2916
ASTConsumer.h
clang::Sema::VTableUse
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition: Sema.h:7495
clang::ComparisonCategoryResult::Equal
@ Equal
clang::ASTContext::Char32Ty
CanQualType Char32Ty
Definition: ASTContext.h:1100
clang::Sema::ActOnDecompositionDeclarator
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
Definition: SemaDeclCXX.cpp:711
clang::ExplicitSpecKind::ResolvedTrue
@ ResolvedTrue
clang::VarDecl::evaluateDestruction
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
Definition: ExprConstant.cpp:15113
clang::Sema::TrivialABIHandling
TrivialABIHandling
Definition: Sema.h:3437
clang::DeclContext::Encloses
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1221
clang::CXXRecordDecl::hasTrivialMoveAssignment
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1296
clang::Sema::checkThisInStaticMemberFunctionAttributes
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
Definition: SemaDeclCXX.cpp:18117
clang::Sema::PushOnScopeChains
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1498
clang::Sema::RequireLiteralType
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:8961
clang::Sema::InstantiateFunctionDeclaration
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
Definition: SemaTemplateInstantiateDecl.cpp:5143
clang::DeclContext::isFileContext
bool isFileContext() const
Definition: DeclBase.h:1942
clang::Redeclarable::getMostRecentDecl
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
clang::Sema::ContextRAII
A RAII object to temporarily push a declaration context.
Definition: Sema.h:1156
clang::Type::isOverloadableType
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:7186
clang::BinaryOperatorKind
BinaryOperatorKind
Definition: OperationKinds.h:25
clang::Sema::LookupSingleName
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
Definition: SemaLookup.cpp:3094
RefersToRValueRef
static bool RefersToRValueRef(Expr *MemRef)
Definition: SemaDeclCXX.cpp:4785
clang::NOUR_Unevaluated
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:162
clang::TemplateParameterList::size
unsigned size() const
Definition: DeclTemplate.h:129
clang::Sema::CurrentInstantiationScope
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9581
clang::VarDecl::getInit
const Expr * getInit() const
Definition: Decl.h:1284
clang::Sema::AbstractVariableType
@ AbstractVariableType
Definition: Sema.h:7803
clang::CXXRecordDecl::hasTrivialDestructor
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1321
clang::ExprValueKind
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:117
clang::AttributeCommonInfo::IgnoredAttribute
@ IgnoredAttribute
Definition: AttributeCommonInfo.h:57
clang::Expr::isValueDependent
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:168
clang::EST_NoThrow
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
Definition: ExceptionSpecificationType.h:25
clang::ConstStmtVisitor
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:193
clang::Sema::BuildDecltypeType
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9157
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
IIK_Inherit
@ IIK_Inherit
Definition: SemaDeclCXX.cpp:4704
CheckConstexprFunctionBody
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
Definition: SemaDeclCXX.cpp:2187
clang::Sema::CreateOverloadedBinOp
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
Definition: SemaOverload.cpp:13596
clang::CXXRecordDecl::finishedDefaultedOrDeletedMember
void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD)
Indicates that the declaration of a defaulted or deleted special member function is now complete.
Definition: DeclCXX.cpp:1396
clang::ObjCRuntime
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
clang::FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:2996
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:764
clang::Sema::CheckConstraintSatisfaction
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, ArrayRef< TemplateArgument > TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: SemaConcept.cpp:312
clang::RecordDecl::field_end
field_iterator field_end() const
Definition: Decl.h:4108
clang::Scope::setEntity
void setEntity(DeclContext *E)
Definition: Scope.h:351
clang::BaseUsingDecl::shadow_begin
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3374
clang::Sema::lookupStdExperimentalNamespace
NamespaceDecl * lookupStdExperimentalNamespace()
Definition: SemaDeclCXX.cpp:11292
clang::FunctionDecl::setDefaultedFunctionInfo
void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info)
Definition: Decl.cpp:2959
clang::Sema::CheckConstexprKind::CheckValid
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
clang::BinaryOperator::getOverloadedOpcode
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2097
clang::Expr::isTemporaryObject
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3082
clang::Sema::CheckEquivalentExceptionSpec
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaExceptionSpec.cpp:291
clang::Sema::MarkDeclRefReferenced
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19230
clang::FieldDecl::getInClassInitStyle
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:2972
getMSPropertyAttr
static const ParsedAttr * getMSPropertyAttr(const ParsedAttributesView &list)
Definition: SemaDeclCXX.cpp:3206
clang::TemplateParameterList::getDepth
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
Definition: DeclTemplate.cpp:156
clang::PartialDiagnostic
Definition: PartialDiagnostic.h:31
clang::CXXRecordDecl::getDestructor
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1888
clang::ASTContext::getElaboratedType
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
Definition: ASTContext.cpp:4957
clang::FunctionDecl::isExternC
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3239
clang::ComparisonCategoryInfo::getType
QualType getType() const
Definition: ComparisonCategories.cpp:166
clang::MSInheritanceModel::Virtual
@ Virtual
clang::MemberPointerType
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2846
clang::VarDecl::getTSCSpec
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1093
CheckOperatorNewDeleteDeclarationScope
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
Definition: SemaDeclCXX.cpp:15715
clang::ASTContext::getLValueReferenceType
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Definition: ASTContext.cpp:3390
clang::Sema::SetIvarInitializers
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)
SetIvarInitializers - This routine builds initialization ASTs for the Objective-C implementation whos...
Definition: SemaDeclCXX.cpp:17891
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::Sema::MaybeCreateExprWithCleanups
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
Definition: SemaExprCXX.cpp:7157
clang::DeclStmt
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1297
clang::Sema::SemaDiagnosticBuilder
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:1940
clang::Sema::propagateDLLAttrToBaseClassTemplate
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
Definition: SemaDeclCXX.cpp:6461
clang::Sema::CheckFunctionDeclaration
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11023
clang::TemplateParameterList::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:197
clang::InitializationKind
Describes the kind of initialization being performed, along with location information for tokens rela...
Definition: Initialization.h:566
lookupOperatorsForDefaultedComparison
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
Definition: SemaDeclCXX.cpp:8476
hasOneRealArgument
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
Definition: SemaDeclCXX.cpp:15427
clang::ActionResult< Expr * >
clang::Type::isObjCObjectType
bool isObjCObjectType() const
Definition: Type.h:6882
clang::ArrayTypeLoc
Wrapper for source info for arrays.
Definition: TypeLoc.h:1516
clang::Sema::BuildExceptionDeclaration
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
Definition: SemaDeclCXX.cpp:16364
clang::Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:9107
clang::FunctionProtoType::ExceptionSpecInfo::Type
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3959
clang::DeclSpec::getRepAsDecl
Decl * getRepAsDecl() const
Definition: DeclSpec.h:490
clang::BaseUsingDecl::addShadowDecl
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3014
clang::VarDecl::isUsableInConstantExpressions
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2401
clang::FunctionProtoType::ExtProtoInfo::ExceptionSpec
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3989
clang::ElaboratedTypeLoc
Definition: TypeLoc.h:2260
clang::DeclaratorChunk::FunctionTypeInfo::RefQualifierIsLValueRef
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1292
clang::InitializationKind::CreateDirectList
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Definition: Initialization.h:634
clang::CXXThisExpr
Represents the this expression in C++.
Definition: ExprCXX.h:1142
clang::Sema::ExpressionEvaluationContext::ConstantEvaluated
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
ComparisonCategories.h
clang::TypeLoc::IgnoreParens
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1183
clang::Sema::UPPC_StaticAssertExpression
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:8456
clang::Sema::collectUnexpandedParameterPacks
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
Definition: SemaTemplateVariadic.cpp:513
clang::RValueReferenceType
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2828
clang::LazyOffsetPtr::get
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Definition: ExternalASTSource.h:374
defaultedSpecialMemberIsConstexpr
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
Definition: SemaDeclCXX.cpp:7220
clang::Sema::CheckConstexprFunctionDefinition
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
Definition: SemaDeclCXX.cpp:1735
clang::FunctionTypeLoc::getParam
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1464
clang::Sema::CodeSynthesisContext::ExceptionSpecEvaluation
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:9089
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2655
clang::ASTContext::AutoDeductTy
QualType AutoDeductTy
Definition: ASTContext.h:1151
ScopeInfo.h
clang::DeclAccessPair::getAccess
AccessSpecifier getAccess() const
Definition: DeclAccessPair.h:44
clang::FunctionProtoType::exceptions
ArrayRef< QualType > exceptions() const
Definition: Type.h:4279
checkCUDADeviceBuiltinSurfaceClassTemplate
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
Definition: SemaDeclCXX.cpp:6169
clang::ast_matchers::recordType
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
Definition: ASTMatchersInternal.cpp:1059
clang::LangAS::Default
@ Default
clang::DecompositionDeclarator
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1702
clang::DeclaratorDecl::setTypeSourceInfo
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:762
clang::Type::getBaseElementTypeUnsafe
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7213
clang::UnresolvedUsingTypenameDecl::Create
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3132
clang::BinaryOperator::isCompoundAssignmentOp
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:4001
clang::FunctionDecl::isMain
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3084
buildSingleCopyAssignRecursively
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
Definition: SemaDeclCXX.cpp:14111
clang::CXXRecordDecl::needsOverloadResolutionForCopyAssignment
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition: DeclCXX.h:912
clang::CanQual::getUnqualifiedType
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Definition: CanonicalType.h:620
clang::StmtResult
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:263
clang::Sema::CheckDestructorAccess
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
Definition: SemaAccess.cpp:1605
clang::Sema::ActOnForStmt
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2123
clang::Sema::PopPragmaVisibility
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Definition: SemaAttr.cpp:1220
clang::interp::This
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:829
clang::DeclSpec::TQ
TQ
Definition: DeclSpec.h:304
clang::VarDecl::TLS_Dynamic
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:898
clang::Sema::UPPC_FriendDeclaration
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:8468
clang::TypeLoc::getTypeLocClass
TypeLocClass getTypeLocClass() const
Definition: TypeLoc.h:115
clang::CXXConstructorDecl::isCopyConstructor
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2643
clang::Sema::DefineImplicitLambdaToBlockPointerConversion
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
Definition: SemaDeclCXX.cpp:15373
clang::DeclarationName::getNameKind
NameKind getNameKind() const
Determine what kind of name this is.
Definition: DeclarationName.h:382
clang::Sema::CodeSynthesisContext::InitializingStructuredBinding
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:9133
clang::ASTContext::getAddrSpaceQualType
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
Definition: ASTContext.cpp:3023
clang::Sema::isDeclInScope
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false)
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1556
clang::IdentifierInfo::getName
StringRef getName() const
Return the actual identifier string.
Definition: IdentifierTable.h:195
clang::Builtin::ID
ID
Definition: Builtins.h:49
clang::Sema::UnparsedDefaultArgLocs
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:1614
clang::LinkageSpecDecl::Create
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2801
clang::FunctionProtoType::ExtProtoInfo
Extra information about a function prototype.
Definition: Type.h:3983
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::CXXBasePath
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
Definition: CXXInheritance.h:70
clang::CXXRecordDecl::hasTrivialMoveConstructorForCall
bool hasTrivialMoveConstructorForCall() const
Definition: DeclCXX.h:1261
clang::TemplateArgument::Type
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
clang::CXXMethodDecl::isConst
bool isConst() const
Definition: DeclCXX.h:2009
clang::TemplateTypeParmType::getDepth
unsigned getDepth() const
Definition: Type.h:4876
clang::Sema::CheckCompleteVariableDeclaration
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:13253
clang::UnaryOperator::getSubExpr
Expr * getSubExpr() const
Definition: Expr.h:2262
clang::FieldDecl::getParent
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3031
clang::Expr::IgnoreParens
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:2944
PartialDiagnostic.h
clang::UnqualifiedId::ConversionFunctionId
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:986
clang::CXXRecordDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1818
clang::Sema::ProcessDeclAttributes
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
clang::Sema::DiagnoseAbsenceOfOverrideControl
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
Definition: SemaDeclCXX.cpp:3145
clang::Sema::mergeDeclAttributes
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3029
clang
Definition: CalledOnceCheck.h:17
clang::Sema::PushFunctionScope
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2177
clang::LangOptions::MSVC2015
@ MSVC2015
Definition: LangOptions.h:125
clang::Sema::CheckConstexprKind
CheckConstexprKind
Definition: Sema.h:3039
clang::Sema::CreateRecoveryExpr
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20387
clang::IndirectFieldDecl
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3093
clang::InitializedEntity::InitializeMemberFromDefaultMemberInitializer
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
Definition: Initialization.h:393
clang::DeclContext::lookup
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1657
clang::CXXRecordDecl::isLiteral
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.h:1409
clang::UsingShadowDecl::Create
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition: DeclCXX.h:3243
clang::VectorType::getElementType
QualType getElementType() const
Definition: Type.h:3285
checkTrivialClassMembers
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
Definition: SemaDeclCXX.cpp:9706
clang::Sema::CheckTypenameType
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
Definition: SemaTemplate.cpp:10535
clang::Type::isArrayType
bool isArrayType() const
Definition: Type.h:6816
clang::Sema::CheckConvertedConstantExpression
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
Definition: SemaOverload.cpp:5874
clang::UnqualifiedIdKind::IK_ConversionFunctionId
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
clang::Sema::DeclareImplicitCopyConstructor
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
Definition: SemaDeclCXX.cpp:15034
RecursiveASTVisitor.h
clang::Sema::SetCtorInitializers
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers=None)
Definition: SemaDeclCXX.cpp:5145
clang::Sema::SpecialMembersBeingDeclared
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition: Sema.h:1685
clang::NestedNameSpecifier::getAsType
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Definition: NestedNameSpecifier.h:196
clang::TypeResult
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:264
clang::Sema::DiagnoseTemplateParameterShadow
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
Definition: SemaTemplate.cpp:881
CheckConstexprReturnType
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
Definition: SemaDeclCXX.cpp:1702
clang::DeclaratorChunk::FunctionTypeInfo::getRefQualifierLoc
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1441
clang::Sema::VerifyICEDiagnoser
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:12628
clang::Sema::ActOnDocumentableDecl
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:13876
clang::CXXRecordDecl::hasUserDeclaredCopyConstructor
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition: DeclCXX.h:781
clang::UsingEnumDecl::Create
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, EnumDecl *ED)
Definition: DeclCXX.cpp:3066
clang::Sema::CheckConstructorDeclarator
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
Definition: SemaDeclCXX.cpp:10453
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:69
clang::EST_BasicNoexcept
@ EST_BasicNoexcept
noexcept
Definition: ExceptionSpecificationType.h:26
clang::Sema::DiagnoseDeletedDefaultedFunction
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
Definition: SemaDeclCXX.cpp:9473
clang::QualType::withConst
QualType withConst() const
Definition: Type.h:847
clang::Sema::getScopeForContext
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2158
clang::Sema::SpecialMemberOverloadResult::Ambiguous
@ Ambiguous
Definition: Sema.h:1550
clang::VarDecl::isConstexpr
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1478
clang::UnaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:2257
clang::BinaryOperator::getRHS
Expr * getRHS() const
Definition: Expr.h:3912
clang::ComparisonCategoryResult
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
Definition: ComparisonCategories.h:66
clang::Sema::CompleteConstructorCall
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
Definition: SemaDeclCXX.cpp:15675
clang::ComparisonCategoryType::StrongOrdering
@ StrongOrdering
clang::Sema::ActOnExplicitBoolSpecifier
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
Definition: SemaDeclCXX.cpp:13271
clang::MSPropertyDecl
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4107
clang::UsingDecl::hasTypename
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3448
clang::CXXCatchStmt
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
clang::Sema::SpecialMemberIsTrivial
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
Definition: SemaDeclCXX.cpp:9770
clang::CXXRecordDecl::getCanonicalDecl
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:501
clang::ParmVarDecl::hasUninstantiatedDefaultArg
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1785
clang::ParsedAttr::getPropertyDataGetter
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:587
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1803
clang::Sema::ActOnFriendFunctionDecl
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
Definition: SemaDeclCXX.cpp:16938
clang::DeclaratorContext::Condition
@ Condition
LookupStdInitializerList
static ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
Definition: SemaDeclCXX.cpp:11520
clang::UnresolvedUsingValueDecl::Create
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3104
clang::LookupResult::Filter
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:617
clang::Sema::ActOnStartNamespaceDef
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
Definition: SemaDeclCXX.cpp:11113
clang::Sema::getImplicitCodeSegOrSectionAttrForFunction
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:10306
clang::Sema::SpecialMemberOverloadResult::getKind
Kind getKind() const
Definition: Sema.h:1565
clang::TypoCorrection::getCorrectionDecl
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
Definition: TypoCorrection.h:151
clang::ElaboratedTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2278
clang::Sema::isCompleteType
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:2591
clang::Sema::getSpecialMember
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:3487
clang::CXXMethodDecl::getMostRecentDecl
CXXMethodDecl * getMostRecentDecl()
Definition: DeclCXX.h:2060
clang::TargetInfo::CCK_MicrosoftWin64
@ CCK_MicrosoftWin64
Definition: TargetInfo.h:1525
clang::CXXRecordDecl::isInterfaceLike
bool isInterfaceLike() const
Definition: DeclCXX.cpp:1910
clang::ComparisonCategoryInfo::Kind
ComparisonCategoryType Kind
The Kind of the comparison category type.
Definition: ComparisonCategories.h:121
clang::Expr::getType
QualType getType() const
Definition: Expr.h:141
clang::CXXScopeSpec::getScopeRep
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:77
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::CXXBaseSpecifier
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
clang::CorrectionCandidateCallback
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: TypoCorrection.h:281
clang::ASTContext::NumImplicitCopyAssignmentOperatorsDeclared
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3116
clang::CXXRecordDecl::hasDefinition
bool hasDefinition() const
Definition: DeclCXX.h:549
clang::Attr
Attr - This represents one attribute.
Definition: Attr.h:44
clang::LookupResult::Found
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
clang::TypeSourceInfo
A container of type source information.
Definition: Type.h:6473
clang::FunctionType::getReturnType
QualType getReturnType() const
Definition: Type.h:3824
clang::Sema::ActOnIntegerConstant
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3716
clang::NamedDecl::getDeclName
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:311
clang::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
clang::Sema::LookupConstructors
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
Definition: SemaLookup.cpp:3379
clang::DeclSpec::getTypeQualifiers
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:547
clang::Declarator::getTypeObject
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2240
clang::Sema::DelegatingCtorDecls
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition: Sema.h:1057
clang::Sema::checkIllFormedTrivialABIStruct
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
Definition: SemaDeclCXX.cpp:10045
clang::Sema::BuildUsingPackDecl
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
Definition: SemaDeclCXX.cpp:12593
clang::Sema::FilterUsingLookup
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
Definition: SemaDeclCXX.cpp:12261
clang::Sema::ActOnFinishDelayedMemberDeclarations
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
Definition: SemaDeclCXX.cpp:10356
clang::Qualifiers::Const
@ Const
Definition: Type.h:150
clang::Sema::ActOnStartCXXInClassMemberInitializer
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
Definition: SemaDeclCXX.cpp:4008
clang::Sema::EvaluateImplicitExceptionSpec
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
Definition: SemaDeclCXX.cpp:7391
clang::Sema::ActOnCXXThis
ExprResult ActOnCXXThis(SourceLocation loc)
Definition: SemaExprCXX.cpp:1380
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1151
clang::Sema::ActOnDefaultCtorInitializers
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
Definition: SemaDeclCXX.cpp:5761
clang::DeclStmt::decls
decl_range decls()
Definition: Stmt.h:1345
clang::CXXRecordDecl::isAbstract
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1176
clang::LookupResult::getLookupKind
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:253
CheckConstexprDeclStmt
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
Definition: SemaDeclCXX.cpp:1822
clang::Sema::SetDeclDeleted
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
Definition: SemaDeclCXX.cpp:17254
clang::TemplateParameterList::shouldIncludeTypeForArgument
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
Definition: DeclTemplate.cpp:205
unsigned
clang::DeclSpec::isVirtualSpecified
bool isVirtualSpecified() const
Definition: DeclSpec.h:578
clang::CXXRecordDecl::setImplicitCopyConstructorIsDeleted
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:846
clang::CXXRecordDecl::getFinalOverriders
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
Definition: CXXInheritance.cpp:642
clang::FunctionProtoType::ExtProtoInfo::TypeQuals
Qualifiers TypeQuals
Definition: Type.h:3987
CheckConstexprCtorInitializer
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
Definition: SemaDeclCXX.cpp:1969
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:336
clang::ASTContext::NumImplicitDestructors
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3126
clang::Declarator::mayHaveDecompositionDeclarator
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition: DeclSpec.h:2071
clang::DeclarationName::getCXXLiteralIdentifier
IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
Definition: DeclarationName.h:470
clang::Sema::adjustContextForLocalExternDecl
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:6943
clang::DeclarationNameInfo::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
Definition: DeclarationName.h:861
clang::Sema::ActOnFunctionDeclarator
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9195
clang::Sema::isUsualDeallocationFunction
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
Definition: SemaExprCXX.cpp:1603
clang::IfStmt::getThen
Stmt * getThen()
Definition: Stmt.h:2000
clang::Sema::ActOnCondition
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:19633
clang::DeclaratorChunk
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1173
clang::RecordDecl::isMsStruct
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma,...
Definition: Decl.cpp:4663
clang::Sema::StdNamespace
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:1292
clang::Sema::ForceDeclarationOfImplicitMembers
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
Definition: SemaLookup.cpp:1032
clang::Sema::isSFINAEContext
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
Definition: SemaTemplateInstantiate.cpp:827
clang::FunctionDecl::isExplicitlyDefaulted
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2219
clang::Sema::CollectIvarsToConstructOrDestruct
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl< ObjCIvarDecl * > &Ivars)
CollectIvarsToConstructOrDestruct - Collect those ivars which require initialization.
Definition: SemaDeclObjC.cpp:5227
clang::Sema::ActOnMemInitializer
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
Definition: SemaDeclCXX.cpp:4167
clang::InitializedEntity
Describes an entity that is being initialized.
Definition: Initialization.h:47
clang::FunctionDecl::isVariadic
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2940
DiagnoseNamespaceInlineMismatch
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
Definition: SemaDeclCXX.cpp:11088
clang::UnresolvedUsingIfExistsDecl
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:3912
clang::Sema::ActOnConversionDeclarator
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
Definition: SemaDeclCXX.cpp:10894
clang::Sema::ExitDeclaratorContext
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1375
clang::TagDecl::getTagKind
TagKind getTagKind() const
Definition: Decl.h:3529
clang::InitializedEntity::InitializeVariable
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
Definition: Initialization.h:248
clang::CXXBasePath::Access
AccessSpecifier Access
The access along this inheritance path.
Definition: CXXInheritance.h:75
clang::CXXRecordDecl::hasUserProvidedDefaultConstructor
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition: DeclCXX.h:774
clang::ExplicitSpecifier::setKind
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1848
clang::TypedefNameDecl
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3184
clang::VirtSpecifiers::getLastLocation
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2647
clang::FunctionDecl::param_begin
param_iterator param_begin()
Definition: Decl.h:2499
clang::Sema::UPPC_BaseType
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:8444
clang::LookupResult::getFoundDecl
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:517
clang::LookupResult::getAsSingle
DeclClass * getAsSingle() const
Definition: Lookup.h:507
clang::CompoundStmt::body
body_range body()
Definition: Stmt.h:1437
clang::CXXRecordDecl::needsImplicitDestructor
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:988
clang::Sema::ConvertParamDefaultArgument
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
Definition: SemaDeclCXX.cpp:258
clang::Sema::findFailedBooleanCondition
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
Definition: SemaTemplate.cpp:3608
clang::Sema::ActOnParamUnparsedDefaultArgument
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
Definition: SemaDeclCXX.cpp:363
clang::FieldDecl::removeInClassInitializer
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition: Decl.h:3005
checkTupleLikeDecomposition
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
Definition: SemaDeclCXX.cpp:1160
clang::Sema::isMemberAccessibleForDeletion
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
Definition: SemaAccess.cpp:1581
clang::TypeAliasTemplateDecl
Declaration of an alias template.
Definition: DeclTemplate.h:2520
clang::DeclContextLookupResult
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1300
clang::DependentNameTypeLoc::setNameLoc
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2348
clang::FunctionTypeLoc::getReturnLoc
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1467
clang::TemplateParameterList::getMinRequiredArguments
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
Definition: DeclTemplate.cpp:130
isNonlocalVariable
static bool isNonlocalVariable(const Decl *D)
Determine whether the given declaration is a global variable or static data member.
Definition: SemaDeclCXX.cpp:17600
clang::DeclaratorDecl::getNumTemplateParameterLists
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:815
clang::Sema::CreateBuiltinArraySubscriptExpr
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5672
checkForMultipleExportedDefaultConstructors
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
Definition: SemaDeclCXX.cpp:6131
clang::Sema::CheckTypedefForVariablyModifiedType
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6398
clang::ImplicitCastExpr
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3676
clang::Sema::PushUsingDirective
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
Definition: SemaDeclCXX.cpp:11727
clang::Sema::AdjustDeclIfTemplate
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
Definition: SemaTemplate.cpp:898
clang::Sema::handleTagNumbering
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4586
clang::MemberExpr
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3220
clang::TypeLoc::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
clang::DeclSpec::TQ_restrict
@ TQ_restrict
Definition: DeclSpec.h:307
clang::CXXBasePaths
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Definition: CXXInheritance.h:117
clang::ASTContext::getTrivialTypeSourceInfo
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
Definition: ASTContext.cpp:2971
clang::ConstraintSatisfaction
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:28
clang::CXXRecordDecl::hasNonTrivialDestructorForCall
bool hasNonTrivialDestructorForCall() const
Definition: DeclCXX.h:1335
clang::CXXRecordDecl::hasNonTrivialDestructor
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1331
clang::Sema::CheckFriendTypeDecl
FriendDecl * CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo)
Perform semantic analysis of the given friend type declaration.
Definition: SemaDeclCXX.cpp:16641
clang::InClassInitStyle
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:256
clang::QualType::getTypePtr
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6502
clang::Sema::CheckBaseSpecifier
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
Definition: SemaDeclCXX.cpp:2493
clang::Sema::NoteDeletedInheritingConstructor
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
Definition: SemaDeclCXX.cpp:13605
clang::CXXRecordDecl::isDynamicClass
bool isDynamicClass() const
Definition: DeclCXX.h:562
clang::RecordType::getDecl
RecordDecl * getDecl() const
Definition: Type.h:4659
clang::Sema::ActOnCXXMemberDeclarator
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
Definition: SemaDeclCXX.cpp:3273
clang::CanQual::getAs
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
Definition: CanonicalType.h:653
clang::Sema::RequireCompleteEnumDecl
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
Definition: SemaCXXScopeSpec.cpp:241
clang::ASTContext::getPointerType
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Definition: ASTContext.cpp:3270
clang::DeclSpec::TQ_const
@ TQ_const
Definition: DeclSpec.h:306
clang::CPlusPlus11
@ CPlusPlus11
Definition: LangStandard.h:49
clang::InheritingConcreteTypeLoc::getTypePtr
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:502
clang::InitListExpr::getInit
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4892
clang::ComparisonCategoryInfo::ValueInfo
Definition: ComparisonCategories.h:84
clang::CXXScopeSpec::MakeTrivial
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:125
clang::CXXRecordDecl::isPolymorphic
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1169
clang::NamedDecl::isCXXClassMember
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:368
Parent
NodeId Parent
Definition: ASTDiff.cpp:192
clang::ReferenceType
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2766
clang::Sema::getOrCreateStdNamespace
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
Definition: SemaDeclCXX.cpp:11445
clang::Sema::DefaultedFunctionKind::asComparison
DefaultedComparisonKind asComparison() const
Definition: Sema.h:3473
clang::TypoCorrection::WillReplaceSpecifier
void WillReplaceSpecifier(bool ForceReplacement)
Definition: TypoCorrection.h:100
clang::Sema::InheritedConstructorInfo
Definition: SemaDeclCXX.cpp:7105
clang::TargetCXXABI::areArgsDestroyedLeftToRightInCallee
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
Definition: TargetCXXABI.h:190
clang::SourceManager::getExpansionLoc
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
Definition: SourceManager.h:1158
clang::PointerType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2665
clang::Sema::LookupSpecialMember
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
Definition: SemaLookup.cpp:3128
clang::Sema::isImplicitlyDeleted
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
Definition: SemaDeclCXX.cpp:15307
clang::Sema::StdExperimentalNamespaceCache
NamespaceDecl * StdExperimentalNamespaceCache
The C++ "std::experimental" namespace, where the experimental parts of the standard library resides.
Definition: Sema.h:1304
clang::Sema::MarkVariableReferenced
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:19186
clang::Sema::CXXSpecialMember
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1669
clang::LambdaExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:2080
clang::VectorType::getNumElements
unsigned getNumElements() const
Definition: Type.h:3286
clang::FunctionProtoTypeLoc
Definition: TypeLoc.h:1498
computeImplicitExceptionSpec
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
Definition: SemaDeclCXX.cpp:7357
clang::Sema::DiagnoseUnsatisfiedConstraint
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
Definition: SemaConcept.cpp:688
clang::Sema::TPL_TemplateMatch
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:8275
clang::InheritedConstructor
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2395
clang::Decl::setInvalidDecl
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
clang::ASTContext::getArrayDecayedType
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
Definition: ASTContext.cpp:6767
clang::CXXRecordDecl::hasInheritedConstructor
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1369
clang::Sema::BuildBaseInitializer
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
Definition: SemaDeclCXX.cpp:4544
clang::Sema::InheritedConstructorInfo::findConstructorForBase
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
Definition: SemaDeclCXX.cpp:7170
clang::CXXRecordDecl::isLambda
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:999
clang::FunctionDecl::isFunctionTemplateSpecialization
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2693
clang::CXXConstructExpr::getArg
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1611
clang::Sema::CheckCompleteDecompositionDeclaration
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
Definition: SemaDeclCXX.cpp:1470
clang::isTemplateInstantiation
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:197
clang::ASTContext::hasSameType
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2521
clang::Sema::isAbstractType
bool isAbstractType(SourceLocation Loc, QualType T)
Definition: SemaDeclCXX.cpp:5772
clang::Sema::LookupOrdinaryName
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:4305
clang::CXXRecordDecl::hasTrivialCopyConstructor
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1233
clang::Sema::UPPC_DefaultArgument
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:8477
clang::TypeLoc::castAs
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:77
clang::Sema::CXXCopyAssignment
@ CXXCopyAssignment
Definition: Sema.h:1673
clang::LookupResult::getAcceptableDecl
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:361
clang::ASTContext::NumImplicitMoveConstructors
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3105
clang::Sema::BuildUsingEnumDeclaration
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, EnumDecl *ED)
Definition: SemaDeclCXX.cpp:12538
clang::Sema::ImplicitExceptionSpecification
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:6234
llvm::SmallVectorImpl
Definition: LLVM.h:39
clang::TagDecl::isDependentType
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3488
clang::Sema::DefineImplicitLambdaToFunctionPointerConversion
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
Definition: SemaDeclCXX.cpp:15311
clang::Sema::CheckForImmediateInvocation
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17116
clang::Scope::DeclScope
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:59
CheckAbstractClassUsage
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
Definition: SemaDeclCXX.cpp:5974
clang::TypeAliasDecl
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3306
clang::CXXRecordDecl::hasUserDeclaredDestructor
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:982
clang::CallExpr::arguments
arg_range arguments()
Definition: Expr.h:3092
clang::EST_NoexceptFalse
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
Definition: ExceptionSpecificationType.h:28
clang::Sema::HandleDeclarator
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:5939
CheckConstexprDestructorSubobjects
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
Definition: SemaDeclCXX.cpp:1650
clang::SC_None
@ SC_None
Definition: Specifiers.h:235
clang::ValueDecl::getType
QualType getType() const
Definition: Decl.h:686
clang::Sema::ActOnCompoundStmt
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition: SemaStmt.cpp:409
true
#define true
Definition: stdbool.h:21
InitializationHasSideEffects
static bool InitializationHasSideEffects(const FieldDecl &FD)
Definition: SemaDeclCXX.cpp:3196
clang::Sema::referenceDLLExportedClassMethods
void referenceDLLExportedClassMethods()
Definition: SemaDeclCXX.cpp:13855
clang::Type::isIntegerType
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7089
clang::Sema::TUK_Friend
@ TUK_Friend
Definition: Sema.h:3380
getNamespaceDecl
static NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
Definition: SemaDeclCXX.cpp:11258
clang::RecordDecl::setParamDestroyedInCallee
void setParamDestroyedInCallee(bool V)
Definition: Decl.h:4051
clang::Sema::getPrintingPolicy
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:3326
clang::VarTemplateDecl
Declaration of a variable template.
Definition: DeclTemplate.h:3079
clang::EvaluatedExprVisitor
EvaluatedExprVisitor - This class visits 'Expr *'s.
Definition: EvaluatedExprVisitor.h:128
clang::ASTContext::hasSameUnqualifiedType
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2545
clang::ArrayType::getElementType
QualType getElementType() const
Definition: Type.h:2919
clang::Sema::ParsingInitForAutoVars
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:1028
Previous
StateNode * Previous
Definition: UnwrappedLineFormatter.cpp:1085
clang::ParsedAttributesView
Definition: ParsedAttr.h:909
clang::Expr
This represents one expression.
Definition: Expr.h:109
clang::BaseUsingDecl
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3304
clang::Sema::ActOnAccessSpecifier
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Definition: SemaDeclCXX.cpp:3048
clang::FieldDecl::getCanonicalDecl
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3042
clang::IndirectFieldDecl::chain
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3115
clang::DeclAccessPair::getDecl
NamedDecl * getDecl() const
Definition: DeclAccessPair.h:41
clang::CXXScopeSpec::isEmpty
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:190
clang::TargetInfo::shouldDLLImportComdatSymbols
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1196
clang::FunctionDecl::getDescribedFunctionTemplate
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3733
clang::Type::isSpecificBuiltinType
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7026
clang::Sema::CodeSynthesisContext::Entity
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:9152
findTrivialSpecialMember
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
Definition: SemaDeclCXX.cpp:9500
clang::CXXRecordDecl::defaultedMoveConstructorIsDeleted
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition: DeclCXX.h:694
clang::ConstructorUsingShadowDecl
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3485
clang::Sema::checkSYCLDeviceFunction
bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaSYCL.cpp:4014
IIK_Default
@ IIK_Default
Definition: SemaDeclCXX.cpp:4701
clang::Sema::HandleMSProperty
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
Definition: SemaDeclCXX.cpp:18252
TryNamespaceTypoCorrection
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
Definition: SemaDeclCXX.cpp:11616
clang::ParmVarDecl::Create
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2770
clang::CXXConstructExpr::Create
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, ConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition: ExprCXX.cpp:1032
clang::UnqualifiedId::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1159
clang::Sema::SetDelegatingInitializer
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
Definition: SemaDeclCXX.cpp:5124
clang::CXXDefaultInitExpr
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1318
clang::Sema::isCurrentClassName
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
Definition: SemaDeclCXX.cpp:2424
clang::CXXScopeSpec::getRange
SourceRange getRange() const
Definition: DeclSpec.h:69
clang::CXXRecordDecl::defaultedDestructorIsConstexpr
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1311
clang::CXXCtorInitializer
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2192
clang::Sema::isStdInitializerList
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
Definition: SemaDeclCXX.cpp:11460
clang::CXXConstructorDecl::isMoveConstructor
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition: DeclCXX.cpp:2648
clang::Sema::DefineUsedVTables
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
Definition: SemaDeclCXX.cpp:17757
clang::Sema::DefaultedFunctionKind::asSpecialMember
CXXSpecialMember asSpecialMember() const
Definition: Sema.h:3472
clang::Sema::UPPC_RequiresClause
@ UPPC_RequiresClause
Definition: Sema.h:8507
clang::Sema::getCurrentThisType
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
Definition: SemaExprCXX.cpp:1190
clang::LinkageSpecDecl::setRBraceLoc
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2863
clang::TSK_ImplicitInstantiation
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:179
clang::QualType::addConst
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:844
BuildImplicitBaseInitializer
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
Definition: SemaDeclCXX.cpp:4708
clang::Sema::PP
Preprocessor & PP
Definition: Sema.h:586
clang::EnumType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:4675
clang::Sema::BuildReferenceType
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:2184
clang::UnqualifiedIdKind::IK_ImplicitSelfParam
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
clang::DeclContext::isFunctionOrMethod
bool isFunctionOrMethod() const
Definition: DeclBase.h:1924
clang::CXXScopeSpec::getBeginLoc
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:73
clang::DeclaratorChunk::ParamInfo::DefaultArgTokens
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1261
clang::Sema::LookupUsingDeclName
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:4332
clang::ASTContext::NumImplicitMoveAssignmentOperatorsDeclared
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3123
clang::FunctionProtoType::getExtParameterInfo
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4313
clang::Sema::CheckUsingShadowDecl
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
Definition: SemaDeclCXX.cpp:11882
clang::FunctionProtoType::getExtProtoInfo
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4121
clang::DeclSpec::getConstexprSpecLoc
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:758
clang::DeclarationNameInfo::getLoc
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
Definition: DeclarationName.h:785
clang::Sema::MarkFunctionReferenced
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:17551
clang::DeclarationNameInfo
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Definition: DeclarationName.h:756
clang::ClassTemplateSpecializationDecl
Represents a class template specialization, which refers to a class template with a given set of temp...
Definition: DeclTemplate.h:1803
clang::TST_decltype_auto
@ TST_decltype_auto
Definition: Specifiers.h:87
clang::DeclSpec::TST_auto
static const TST TST_auto
Definition: DeclSpec.h:294
clang::Sema::CheckDelegatingCtorCycles
void CheckDelegatingCtorCycles()
Definition: SemaDeclCXX.cpp:18009
CheckOperatorDeleteDeclaration
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
Definition: SemaDeclCXX.cpp:15846
clang::ParsedAttr::getPropertyDataSetter
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:593
clang::LocalInstantiationScope::isLocalPackExpansion
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
Definition: SemaTemplateInstantiate.cpp:3749
clang::InitializationKind::CreateCopy
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Definition: Initialization.h:673
clang::ComparisonCategories::getResultString
static StringRef getResultString(ComparisonCategoryResult Kind)
Definition: ComparisonCategories.cpp:184
clang::FunctionDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2487
clang::CXXThisExpr::isImplicit
bool isImplicit() const
Definition: ExprCXX.h:1159
clang::TargetInfo::CallingConvKind
CallingConvKind
Definition: TargetInfo.h:1522
clang::FunctionDecl::setBody
void setBody(Stmt *B)
Definition: Decl.cpp:3064
clang::ASTContext::CreateTypeSourceInfo
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
Definition: ASTContext.cpp:2957
clang::Sema::BuildBlockForLambdaConversion
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
Definition: SemaLambda.cpp:1978
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:424
clang::FieldDecl::isAnonymousStructOrUnion
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4208
clang::CXXRecordDecl::getTemplateInstantiationPattern
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1843
clang::OverloadCandidateSet::CSK_Operator
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:946
RemoveAddressSpaceFromPtr
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
Definition: SemaDeclCXX.cpp:15734
clang::Sema::CodeSynthesisContext::Kind
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
clang::Decl::setReferenced
void setReferenced(bool R=true)
Definition: DeclBase.h:587
clang::Decl::addAttr
void addAttr(Attr *A)
Definition: DeclBase.cpp:885
clang::ASTContext::BoolTy
CanQualType BoolTy
Definition: ASTContext.h:1093
clang::DeclRefExpr
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1223
clang::Sema::AbstractDiagSelID
AbstractDiagSelID
Definition: Sema.h:7799
clang::Sema::ActOnPureSpecifier
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
Definition: SemaDeclCXX.cpp:17589
clang::NamespaceDecl
Represent a C++ namespace.
Definition: Decl.h:541
clang::DeclContextLookupResult::empty
bool empty() const
Definition: DeclBase.h:1321
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1856
clang::Sema::ComparisonCategoryUsage::DefaultedOperator
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
isIncompleteOrZeroLengthArrayType
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
Definition: SemaDeclCXX.cpp:5041
clang::TemplateTypeParmDecl::getDepth
unsigned getDepth() const
Retrieve the depth of the template parameter.
Definition: DeclTemplate.cpp:678
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3885
clang::CXXRecordDecl::hasTrivialCopyAssignment
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1283
clang::Sema::ActOnFinishCXXMemberSpecification
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDeclCXX.cpp:10119
clang::DeclarationNameTable::getCXXConstructorName
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
Definition: DeclarationName.cpp:310
clang::DeclContext::Equals
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:1996
clang::CompoundStmt::Create
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:379
clang::TypeWithKeyword::getTagTypeKindName
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:5465
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2853
clang::DeclSpec::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:507
clang::Type::getCanonicalTypeUnqualified
CanQualType getCanonicalTypeUnqualified() const
Definition: CanonicalType.h:214
clang::BaseUsingDecl::shadow_size
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3382
clang::LookupResult::FoundUnresolvedValue
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
clang::InitListExpr::getNumInits
unsigned getNumInits() const
Definition: Expr.h:4874
clang::FunctionDecl::getStorageClass
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2584
clang::CXXOperatorCallExpr
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:82
clang::DeclarationNameInfo::getBeginLoc
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
Definition: DeclarationName.h:858
checkTrivialSubobjectCall
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, Sema::CXXSpecialMember CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
Definition: SemaDeclCXX.cpp:9655
clang::LookupResult::getLookupNameInfo
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:233
clang::NamespaceDecl::isInline
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:602
checkArrayDecomposition
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
Definition: SemaDeclCXX.cpp:947
clang::CXXConstructExpr
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1460
clang::Decl::setLocalOwningModule
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:768
clang::FunctionDecl::isDefined
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3019
lookupStdTypeTraitMember
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
Definition: SemaDeclCXX.cpp:996
clang::ActionResult::isUsable
bool isUsable() const
Definition: Ownership.h:166
clang::StringLiteral::getString
StringRef getString() const
Definition: Expr.h:1850
clang::Sema::SpecialMemberCache
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:1580
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:782
clang::UnqualifiedId::getKind
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1032
clang::CXXMemberCallExpr
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:177
clang::CharUnits::getQuantity
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
clang::CXXScopeSpec::isNotEmpty
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:192
clang::LookupResult::getRepresentativeDecl
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:524
clang::DeclaratorContext::AliasDecl
@ AliasDecl
clang::Preprocessor::getIdentifierInfo
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:1284
clang::DeclSpec::getAtomicSpecLoc
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:551
clang::Sema::DefineDefaultedComparison
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
Definition: SemaDeclCXX.cpp:8785
clang::Sema::BuildStdInitializerList
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
Definition: SemaDeclCXX.cpp:11554
clang::DeclaratorDecl::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:756
clang::FixItHint::CreateReplacement
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
clang::ParmVarDecl::hasInheritedDefaultArg
bool hasInheritedDefaultArg() const
Definition: Decl.h:1797
clang::Sema::CheckLiteralOperatorDeclaration
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
Definition: SemaDeclCXX.cpp:16104
clang::Sema::CodeSynthesisContext::MarkingClassDllexported
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:9136
clang::CXXRecordDecl::setTrivialForCallFlags
void setTrivialForCallFlags(CXXMethodDecl *MD)
Definition: DeclCXX.cpp:1453
clang::ICIS_NoInit
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:257
clang::NamespaceDecl::getAnonymousNamespace
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:636
AddMostOverridenMethods
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
Definition: SemaDeclCXX.cpp:9976
clang::ASTContext::getCanonicalNestedNameSpecifier
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
Definition: ASTContext.cpp:6619
clang::DeclSpec
Captures information about "declaration specifiers".
Definition: DeclSpec.h:229
clang::CXXMethodDecl::isVirtual
bool isVirtual() const
Definition: DeclCXX.h:2012
clang::Declarator::isRedeclaration
bool isRedeclaration() const
Definition: DeclSpec.h:2602
clang::DeclSpec::SCS_extern
@ SCS_extern
Definition: DeclSpec.h:236
clang::VarDecl::setExceptionVariable
void setExceptionVariable(bool EV)
Definition: Decl.h:1406
clang::Sema::CheckCUDACall
bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:789
clang::Sema::UPPC_DataMemberType
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:8450
RecordLayout.h
clang::Sema::UPPC_UsingDeclaration
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:8465
clang::ento::ObjKind::OS
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
clang::Sema::AdjustDestructorExceptionSpec
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Definition: SemaDeclCXX.cpp:13866
clang::Sema::ActOnBaseSpecifier
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
Definition: SemaDeclCXX.cpp:2644
clang::ReturnStmt
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2765
clang::Sema::CheckBaseClassAccess
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
Definition: SemaAccess.cpp:1861
clang::prec::Spaceship
@ Spaceship
Definition: OperatorPrecedence.h:38
TypeLoc.h
clang::VarDecl::evaluateValue
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2447
clang::declaresSameEntity
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1206
clang::TypeSourceInfo::getTypeLoc
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
clang::UnqualifiedIdKind::IK_ConstructorTemplateId
@ IK_ConstructorTemplateId
A constructor named via a template-id.
clang::ValueDecl::setType
void setType(QualType newType)
Definition: Decl.h:687
ParsedTemplate.h
clang::Sema::checkThisInStaticMemberFunctionExceptionSpec
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
Definition: SemaDeclCXX.cpp:18075
clang::CXXRecordDecl::needsImplicitDefaultConstructor
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:754
clang::StmtError
StmtResult StmtError()
Definition: Ownership.h:279
clang::LValueReferenceType
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2810
Initialization.h
clang::VirtSpecifiers
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2615
clang::CXXMethodDecl::getParent
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2083
clang::CXXMethodDecl
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1968
clang::TypeLoc::getNextTypeLoc
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:169
clang::CXXScopeSpec::isInvalid
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:195
clang::NamedDecl::setModulePrivate
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:634
clang::FixItHint::CreateInsertionFromRange
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition: Diagnostic.h:110
clang::Type::isUndeducedType
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7179
clang::Declarator::getMutableDeclSpec
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1917
clang::Sema::ActOnFinishInlineFunctionDef
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:14268
clang::LookupResult::isAmbiguous
bool isAmbiguous() const
Definition: Lookup.h:301
clang::TypeSpecifierType
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:52
clang::ConstexprSpecKind::Unspecified
@ Unspecified
clang::Sema::CorrectDelayedTyposInExpr
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Definition: SemaExprCXX.cpp:8573
clang::Decl::getDeclContext
DeclContext * getDeclContext()
Definition: DeclBase.h:433
clang::Sema::DelayedEquivalentExceptionSpecChecks
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition: Sema.h:1071
clang::Sema::BuildUsingDeclaration
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
Definition: SemaDeclCXX.cpp:12284
clang::Sema::ExpressionEvaluationContext::PotentiallyEvaluated
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
clang::SourceManager::getSpellingLoc
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
Definition: SourceManager.h:1206
DiagnoseBaseOrMemInitializerOrder
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
Definition: SemaDeclCXX.cpp:5359
clang::Sema::CheckStructuredBindingMemberAccess
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
Definition: SemaAccess.cpp:1750
clang::StorageClass
StorageClass
Storage classes.
Definition: Specifiers.h:233
clang::DeclContext::decls_begin
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1431
clang::Sema::ActOnEmptyDeclaration
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
Definition: SemaDeclCXX.cpp:16349
clang::DeclSpec::getThreadStorageClassSpec
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:441